如何拆分字符串输入并附加到列表中?Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25268317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a string input and append to a list? Python
提问by user3934043
I want to ask the user what foods they have ate, then split that input up into a list. Right now, the code is spitting out just empty brackets.
我想询问用户他们吃了什么食物,然后将输入分成一个列表。现在,代码只是吐出空括号。
Also, this is my first post on here, so I apologize in advance for any formating errors.
另外,这是我在这里的第一篇文章,所以我提前为任何格式错误道歉。
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
回答by TheSoundDefense
for i in words:
list_of_food = list_of_food.append(i)
You should change this just to
您应该将其更改为
for i in words:
list_of_food.append(i)
For two different reasons. First, list.append()is an in-place operator, so you don't need to worry about reassigning your list when you use it. Second, when you're trying to use a global variable inside a function, you either need to declare it as globalor never assign to it. Otherwise, the only thing you'll be doing is modifying a local. This is what you're probably trying to do with your function.
出于两个不同的原因。首先,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)
However, because you shouldn't use globals unless absolutely necessary (it's not a great practice), this is the best method:
但是,因为除非绝对必要,否则不应使用全局变量(这不是一个很好的做法),所以这是最好的方法:
def split_food(input, food_list):
#split the input
words = input.split()
for i in words:
food_list.append(i)
return food_list
回答by Ashok Kumar Jayaraman
>>> 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)
回答by Partiban Ramasamy
Use the "extend" keyword. This aggregates two lists together.
使用“扩展”关键字。这将两个列表聚合在一起。
list_of_food = []
def split_food(input):
#split the input
words = input.split()
list_of_food.extend(words)
print list_of_food

