我不确定为什么这行不通。我正在尝试从一个很长的单词列表中进行迭代,并将字符转换为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)
答案 0 :(得分:0)
在Python中,具有副作用并在适当位置修改对象(例如append()或sort())的方法或函数显式返回None。
这是为了避免与函数样式(如sorted())混淆,在函数样式中,返回值是新分配的对象,而原始值则保持不变。 source
如果要在一行中执行此操作,则可以在Python中添加带有“ +”号的列表,因为与extend不同,添加操作不会修改原始列表。
inputs.append(set([len(item.split(","))] + [0.0 for i in range(1, len(item))]))
我也要补充一点,似乎“ set”一词或“ [0.0 for range(1,len(item))]中的i”部分都需要添加,您正在创建一个包含多个0.0的列表只拿一套。照原样,您将不会为每个字符代表一个占位符。