2

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)
1

4 Answers 4

3

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']]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.