如何分割字符串输入并附加到列表中?Python

2024-04-29 05:57:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问用户他们吃了什么食物,然后把输入分成一个列表。现在,代码只吐出了空括号。

此外,这是我在这里的第一篇文章,因此我为任何格式错误预先道歉。

list_of_food = []


def split_food(input):

    #split the input
    words = input.split()

    for i in words:
        list_of_food = list_of_food.append(i)

print list_of_food

Tags: of代码用户列表inputfooddef格式
3条回答

使用“extend”关键字。这将两个列表聚合在一起。

list_of_food = []


def split_food(input):

    #split the input
    words = input.split()
    list_of_food.extend(words)

print list_of_food
>>> text = "What can I say about this place. The staff of these restaurants is nice and the eggplant is not bad.'
>>> txt1 = text.split('.')
>>> txt2 = [line.split() for line in txt1]
>>> new_list = []
>>> for i in range(0, len(txt2)):
        l1 = txt2[i]
        for w in l1:
          new_list.append(w)
print(new_list)
for i in words:
    list_of_food = list_of_food.append(i)

你应该把这个改成

for i in words:
    list_of_food.append(i)

有两个不同的原因。首先,list.append()是一个就地运算符,因此在使用列表时不必担心重新分配列表。其次,当您试图在函数中使用全局变量时,您要么需要将其声明为global,要么永远不要为其赋值。否则,您将要做的唯一事情就是修改本地。这可能是你想用你的函数做的。

def split_food(input):

    global list_of_food

    #split the input
    words = input.split()

    for i in words:
        list_of_food.append(i)

但是,因为除非绝对必要(这不是一个很好的实践),否则不应该使用globals,所以这是最好的方法:

def split_food(input, food_list):

    #split the input
    words = input.split()

    for i in words:
        food_list.append(i)

    return food_list

相关问题 更多 >