【问题标题】:How to split a string input and append to a list? Python如何拆分字符串输入并附加到列表? Python
【发布时间】:2014-08-12 15:28:39
【问题描述】:

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

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

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


【解决方案1】:
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

【讨论】:

  • 或者更好的是,跳过for循环并使用list_of_food.extend(words)
  • 根本不需要list_of_food 是吗?拆分后,单词将成为一个列表。
  • @Robert Moskal 如果你想返回,无论如何 append 都会修改你的列表
【解决方案2】:
>>> 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()already 返回一个列表,因此您遍历一个列表以逐个元素复制到另一个列表
【解决方案3】:

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

list_of_food = []


def split_food(input):

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

print list_of_food

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    相关资源
    最近更新 更多