这是我的代码:
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'
作为输出,就好像它只是抓住了一样从第二个元素开始,而不是迭代。
答案 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