Python While在for循环中为列表列表循环
我正在尝试创建一个包含字符串列表的大列表。我迭代输入字符串列表并创建一个临时列表。 输入: 我的期望输出:Python While在for循环中为列表列表循环,python,list,for-loop,Python,List,For Loop,我正在尝试创建一个包含字符串列表的大列表。我迭代输入字符串列表并创建一个临时列表。 输入: 我的期望输出: [['Mike','Angela','Bill'],['Robert','Pam']...] 我得到的是: [['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...] 代码: for i in range(0,len(temp)): temporary = [] while(temp[i] != '\
[['Mike','Angela','Bill'],['Robert','Pam']...]
我得到的是:
[['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...]
代码:
for i in range(0,len(temp)):
temporary = []
while(temp[i] != '\n' and i<len(temp)-1):
temporary.append(temp[i])
i+=1
bigList.append(temporary)
对于范围(0,len(temp))内的i:
临时=[]
而(temp[i]!='\n'和i使用itertools.groupby
from itertools import groupby
names = ['Mike','Angela','Bill','\n','Robert','Pam']
[list(g) for k,g in groupby(names, lambda x:x=='\n') if not k]
#[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]
修复代码时,我建议直接迭代每个元素,并将其附加到嵌套列表中-
r = [[]]
for i in temp:
if i.strip():
r[-1].append(i)
else:
r.append([])
请注意,如果temp
以换行符结尾,r
将有一个尾随的空[]
列表。您可以通过以下方式摆脱该列表:
if not r[-1]:
del r[-1]
另一种选择是使用另一位回答者已经提到的itertools.groupby
。不过,您的方法性能更好。您可以尝试:
a_list = ['Mike','Angela','Bill','\n','Robert','Pam','\n']
result = []
start = 0
end = 0
for indx, name in enumerate(a_list):
if name == '\n':
end = indx
sublist = a_list[start:end]
if sublist:
result.append(sublist)
start = indx + 1
>>> result
[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]
for循环在temp数组上扫描得很好,但是内部的while循环正在推进该索引。然后while循环将减少该索引。这导致了重复
temp = ['mike','angela','bill','\n','robert','pam','\n','liz','anya','\n']
# !make sure to include this '\n' at the end of temp!
bigList = []
temporary = []
for i in range(0,len(temp)):
if(temp[i] != '\n'):
temporary.append(temp[i])
print(temporary)
else:
print(temporary)
bigList.append(temporary)
temporary = []
似乎是您可能想要调查的内容。
temp = ['mike','angela','bill','\n','robert','pam','\n','liz','anya','\n']
# !make sure to include this '\n' at the end of temp!
bigList = []
temporary = []
for i in range(0,len(temp)):
if(temp[i] != '\n'):
temporary.append(temp[i])
print(temporary)
else:
print(temporary)
bigList.append(temporary)
temporary = []