创建一个包含从另一个列表中弹出的元素的列表(Python)

时间:2020-04-27 17:11:20

标签: python list loops for-loop iteration

这是我的代码:

txt = '''food: bacon, eggs, toast

drinks: orange juice, coffee'''

groups = txt.split('\n\n')
for group in groups:
    nameslist = group.split(': ').pop(0)

print(groups)
print(nameslist)

打印(组)的输出符合预期:['food: bacon, eggs, toast', 'drinks: orange juice, coffee']

我正在尝试获取列表['food', 'drinks']作为 print(nameslist)的输出,但是Python给了我'drinks'作为输出,就好像它只是抓住了一样从第二个元素开始,而不是迭代。

2 个答案:

答案 0 :(得分:3)

您的方法存在的问题是,nameslist从未被初始化,并且每次迭代都会被重置,您可能想这样做:

txt = '''food: bacon, eggs, toast

drinks: orange juice, coffee'''

nameslist = [] # initialize namelist
groups = txt.split('\n\n')
for group in groups:
    nameslist.append(group.split(': ').pop(0)) # append instead of overwriting

print(groups)
print(nameslist)  # ['food', 'drinks']

此外,您可以放弃循环并使用list comprehension来实现:

namelist = [x.split(':')[0] for x in groups]  # ['food', 'drinks']

答案 1 :(得分:1)

您当前的设置方式是,您没有在列表中添加任何内容。您只需将变量名称列表设置为最后一个弹出窗口。试试这个:

nameslist = []  # Define an empty list
groups = txt.split('\n\n')
for group in groups:
    nameslist.append(group.split(': ').pop(0)) #Add popped element to the list