简体   繁体   中英

Is there a better way to iterate through list of lists?

I have a long list of sublists looking like this: [[A,B,C,D],[A,B,C,D],[A,B,C,D]].

What I want to do is Join all the A lists together, all the B lists together, etc...

I have found a way of doing this but it is not very elegant, and not elegant at all when the list gets very long. So I was wondering if there was a practical way of solving this.

I have tried indexing through the list. And this works fine but as I mentioned above my solution (shown below) is not good for long lists. I have tried indexing with the mod (%) operator, but this won't work since I have index 2 and 4 in my list which will yield 0 for bot at 4 eg

self.Input_full = [[listA],[listB],[listC],[listD],[listA],etc...]
for sublist in self.Input_full:
            for list in sublist:
                if sublist.index(list) == 0 or sublist.index(list) == 4 or sublist.index(list) == 8:
                    self.X_sent.append(list)
                elif sublist.index(list) == 1 or sublist.index(list) == 5 or sublist.index(list) == 9:
                    self.Y_sent.append(list)
                elif sublist.index(list) == 2 or sublist.index(list) == 6 or sublist.index(list) == 10:
                    self.Ang_sent.append(list)
                else:
                    self.T_sent.append(list)

The desired output is to get One list with all the lists A, one with all the lists B, etc...

Use unpacking with zip :

long_list = [["A","B","C","D"],["A","B","C","D"],["A","B","C","D"]]
grouped_list = list(zip(*long_list))
print(grouped_list)

Output:

[('A', 'A', 'A'), ('B', 'B', 'B'), ('C', 'C', 'C'), ('D', 'D', 'D')]

In case your long_list is of uneven lengths, such as one list contains "E" whereas others don't, use itertools.zip_longest :

from itertools import zip_longest

long_list = [["A","B","C","D"],["A","B","C","D"],["A","B","C","D","E"]]
grouped_list = list(zip_longest(*long_list))
print(grouped_list)

Output:

[('A', 'A', 'A'),
 ('B', 'B', 'B'),
 ('C', 'C', 'C'),
 ('D', 'D', 'D'),
 (None, None, 'E')]

您可能想要拼合列表:

flat_list = [item for sublist in self.Input_full for item in sublist]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM