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

问题描述 投票:0回答:4

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

此外,这是我在这里发表的第一篇文章,因此对于任何格式错误,我提前表示歉意。

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
python string input append
4个回答
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

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)

1
投票

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

list_of_food = []


def split_food(input):

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

print list_of_food

0
投票

食物列表 = []

def split_food(输入):

#split the input
words = input.split()

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

打印食物列表

© www.soinside.com 2019 - 2024. All rights reserved.