列表列表的for循环中的While循环

2024-06-28 19:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个包含字符串列表的大列表。我迭代字符串的输入列表并创建一个临时列表。 输入:

['Mike','Angela','Bill','\n','Robert','Pam','\n',...]

我想要的输出:

^{pr2}$

我得到的是:

^{3}$

代码:

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)

Tags: 字符串代码in列表forlenroberttemp
3条回答

使用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']]

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 = []

修复代码时,我建议直接迭代每个元素,并附加到嵌套列表中-

r = [[]]
for i in temp:
    if i.strip():
        r[-1].append(i)
    else:
        r.append([])

注意,如果temp以换行结尾,r将有一个尾随的空[]列表。不过,你可以摆脱它:

^{pr2}$

另一个选择是使用itertools.groupby,另一个答案者已经提到了这一点。不过,你的方法更有效。在

相关问题 更多 >