0

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 e.g.

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...

  • 1
    "What I want to do is Join all the A lists together, all the B lists together, etc..." It's not clear what you really want to do. If you can give the specific output you're looking for along with the input, someone may have an idea of how to get there. – Michael Geary Aug 05 '19 at 07:24
  • You can use [itertools.chain.from_iterable](https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable). [Here](https://stackoverflow.com/questions/50775024/itertools-chain-from-iterable)'s a detailed explanation. – Javier Aug 05 '19 at 07:24

2 Answers2

3

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')]
Chris
  • 29,127
  • 3
  • 28
  • 51
2

You would probably want to flatten the list:

flat_list = [item for sublist in self.Input_full for item in sublist]
Carsten
  • 2,765
  • 1
  • 13
  • 28