如何拆分字符串输入并附加到列表?蟒蛇

时间:2014-08-12 15:28:40

标签: python string input append

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

另外,这是我在这里的第一篇文章,所以我提前为任何格式化错误道歉。

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

3 个答案:

答案 0 :(得分:2)

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)

但是,因为除非绝对必要,否则不应该使用全局变量(这不是一个好习惯),这是最好的方法:

def split_food(input, food_list):

    #split the input
    words = input.split()

    for i in words:
        food_list.append(i)

    return food_list

答案 1 :(得分:1)

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

答案 2 :(得分:0)

使用“ extend”关键字。这样会将两个列表汇总在一起。

list_of_food = []


def split_food(input):

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

print list_of_food
相关问题