从另一个列表的元素创建列表会将其转换为NoneType

时间:2014-11-06 21:05:28

标签: python python-3.x

我正在尝试使用单独的单词列表中的单词创建单词列表。例如:

>>> 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

变量'东西'是从用户输入中获取的字符串单词列表。 ' 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。这不是这里发生的事情。

1 个答案:

答案 0 :(得分:3)

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
>>>