python - 从长列表 Python 读取时出现 NoneType 错误
问题描述
我不确定为什么这不起作用。我正在尝试从一个非常长的单词列表中迭代并将字符转换为 ASCII,然后将每个单词添加到一个列表中,该列表包含每个单词的长度集和每个字符的占位符 (0.0)。我试图修复它,假设读取文件的生成器返回“none”,但错误出现在列表生成器中。回溯是:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-180a2950dd2d> in <module>()
35 for item in read_words(r"*pathname*"):
36 if item is not None:
---> 37 inputs.append(set([len(item.split(","))].extend([0.0 for i in range(1, len(item))])))
38 print(inputs)
39 #fitness function
TypeError: 'NoneType' object is not iterable
这是整个代码:
import neat, random
#fast solution for iterating over large wordlist
# playing with the training data a bit
def convert(word):
return [str(ord(i)/122) for i in word]
def read_words(inputfile):
with open(inputfile, 'r') as f:
while True:
buf = f.read(10240)
if not buf:
break
# make sure we end on a space (word boundary)
while not str.isspace(buf[-1]):
ch = f.read(1)
if not ch:
break
buf += ch
words = buf.split()
for word in words:
yield word
yield '' #handle the scene that the file is empty
asciilist = open(r"*pathname*", "w+")
if __name__ == "__main__":
for word in read_words(r"*pathname2*"):
asciilist.write(",".join(convert(word)))
inputs = []
for item in read_words(r"pathname"):
if item is not None:
inputs.append(set([len(item.split(","))].extend([0.0 for i in range(1, len(item))])))
print(inputs)
解决方案
在 Python 中,具有副作用并就地修改对象的方法或函数(如 append() 或 sort())显式返回 None。
这是为了防止与函数式风格(如 sorted())混淆,其中返回值是新分配的对象,而原始值没有改变。资源
如果您想在一行中执行此操作,您可以在 python 中使用“+”号添加列表,因为与扩展不同,添加不会修改原始列表。
inputs.append(set([len(item.split(","))] + [0.0 for i in range(1, len(item))]))
不过,我还要补充一点,似乎“set”字或“[0.0 for i in range(1, len(item))]”部分需要删除,您正在创建一个包含多个 0.0 的列表一套吧。按原样,您不会为每个字符代表一个占位符。
推荐阅读
- python-3.x - JupyterLab - 导入模块
- ruby-on-rails - 如何将 json 数据解析为厨师食谱属性
- reactjs - 我如何解决“动作必须是普通对象。使用自定义中间件进行异步操作。”?
- python - Python List - 过滤特定的文本元素并丢弃剩余的
- php - isMethod 不起作用
- operating-system - 在不复制的情况下交换两个文件中的内容
- vba - 在 Excel 中使用宏替换列标题文本
- testing - PhpStorm 从测试源中排除文件夹
- python - 防止 numpy 将数值向上转换为字符串
- jquery - 在内联可编辑剑道网格中实现类似于 Excel 的“向下复制”功能