擅长:python、mysql、java
<pre><code>for i in words:
list_of_food = list_of_food.append(i)
</code></pre>
<p>你应该把这个改成</p>
<pre><code>for i in words:
list_of_food.append(i)
</code></pre>
<p>有两个不同的原因。首先,<code>list.append()</code>是一个就地运算符,因此在使用列表时不必担心重新分配列表。其次,当您试图在函数中使用全局变量时,您要么需要将其声明为<code>global</code>,要么永远不要为其赋值。否则,您将要做的唯一事情就是修改本地。这可能是你想用你的函数做的。</p>
<pre><code>def split_food(input):
global list_of_food
#split the input
words = input.split()
for i in words:
list_of_food.append(i)
</code></pre>
<p>但是,因为除非绝对必要(这不是一个很好的实践),否则不应该使用globals,所以这是最好的方法:</p>
<pre><code>def split_food(input, food_list):
#split the input
words = input.split()
for i in words:
food_list.append(i)
return food_list
</code></pre>