我正在尝试使用一个单独的单词列表中的单词来创建单词列表。例如:
>>> stuff = ['this', 'is', 'a', 'test']
>>> newlist = [stuff[0]]
>>> newlist
['this']但是,我在尝试这样做的代码中遇到了一个问题,它将新列表转换为一个NoneType对象。
这是抛出错误的代码:
markov_sentence = [stuff[0]]
for i in range(100):
if len(markov_sentence) > 0:
if words_d[markov_sentence[-1]] != []:
newword = random.choice(words_d[markov_sentence[-1]])
markov_sentence = markov_sentence.append(newword)
else:
break
return markov_sentence变量'stuff‘是从用户输入中获取的字符串词的列表。'words_d‘是之前创建的字典,现在并不重要:
stuff = input("Input a series of sentences: ")
stuff = stuff.split()[:-1] #this is here because there was an empty string at the end当我尝试运行这个程序时,我得到的结果是:
Input a series of sentences: this is a test this should work
Traceback (most recent call last):
File "/u/sbiederm/markov.py", line 32, in <module>
main()
File "/u/sbiederm/markov.py", line 29, in main
print(markov(stuff))
File "/u/sbiederm/markov.py", line 18, in markov
if len(markov_sentence) > 0:
TypeError: object of type 'NoneType' has no len()谁能给我解释一下为什么这个列表会变成一个NoneType?我尝试了各种方法来解决这个问题,但我就是想不出来。
编辑:
我已经尝试过了,并且得到了相同的错误:
markov_sentence = []
markov_sentence.append(stuff[0])
Traceback (most recent call last):
File "C:\Python34\markov.py", line 33, in <module>
main()
File "C:\Python34\markov.py", line 30, in main
print(markov(stuff.split()))
File "C:\Python34\markov.py", line 20, in markov
if len(markov_sentence) > 0:
TypeError: object of type 'NoneType' has no len()我看过其他问题,它们没有解释为什么在我的代码中会发生这种情况。我知道.append()返回None。这不是这里正在发生的事情。
发布于 2014-11-07 05:06:52
list.append方法就地修改列表并返回None。也就是说,您需要在它自己的行上调用它,而不是将它赋值给markov_sentence
newword = random.choice(words_d[markov_sentence[-1]])
markov_sentence.append(newword)否则,markov_sentence将被分配给None
>>> lst = [1, 2, 3]
>>> print(lst)
[1, 2, 3]
>>> lst = [1, 2, 3].append(4)
>>> print(lst)
None
>>>https://stackoverflow.com/questions/26789362
复制相似问题