while循环中for循环列表列表

时间:2017-11-27 02:15:20

标签: python list for-loop

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

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

我想要的输出:

[['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)

3 个答案:

答案 0 :(得分: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']]

答案 1 :(得分:0)

你可以尝试:

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

答案 2 :(得分:0)

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