While loop within for loop for list of lists

Viewed 704

I'm trying to create a big list that will contain lists of strings. I iterate over the input list of strings and create a temporary list. Input:

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

My desired output:

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

What i get:

[['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...]

Code:

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)
4 Answers

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

Fixing your code, I'd recommend iterating over each element directly, appending to a nested list -

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

Note that if temp ends with a newline, r will have a trailing empty [] list. You can get rid of that though:

if not r[-1]:
    del r[-1]

Another option would be using itertools.groupby, which the other answerer has already mentioned. Although, your method is more performant.

You could try:

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

Your for loop was scanning over the temp array just fine, but the while loop on the inside was advancing that index. And then your while loop would reduce the index. This caused the repitition.

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