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

3
我想询问用户吃了哪些食物,然后将输入拆分成一个列表。目前,代码只输出空方括号。
此外,这是我在这里的第一篇帖子,所以我提前对任何格式错误表示歉意。
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

欢迎来到SO。下次尝试展示你所尝试的内容。 - Gustavo Meira
看起来像是楼主在那里尝试了那段代码。 - djv
这个回答解决了你的问题吗?如何将字符串拆分为列表? - bad_coder
3个回答

3
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

3
最好跳过for循环,使用list_of_food.extend(words) - chepner
1
根本不需要list_of_food,对吧?一旦你进行拆分,单词就会成为一个列表。 - Robert Moskal
@Robert Moskal如果你想要返回,无论如何append都会修改你的列表。 - user3012759

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)

split()已经返回一个列表,所以你可以迭代一个列表,将元素逐个复制到另一个列表中。 - jps

1
使用"extend"关键字。这将两个列表聚合在一起。
list_of_food = []


def split_food(input):

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

print list_of_food

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接