I’m trying to obtain the combinations of each element in a list within a list. Given this case:
my_list
[[‘A’, ‘B’], [‘C’, ‘D’, ‘E’], [‘F’, ‘G’, ‘H’, ‘I’]]
The output would be:
0 | 1 | |
---|---|---|
0 | A | B |
1 | C | D |
2 | C | E |
3 | D | E |
4 | F | G |
5 | F | H |
6 | F | I |
7 | G | H |
8 | G | I |
9 | H | I |
Or it could also be a new list instead of a DataFrame:
my_new_list
[[‘A’,’B’], [‘C’,’D’], [‘C’,’E’],[‘D’,’E’], [‘F’,’G’],[‘F’,’H’],[‘F’,’I’],[‘G’,’H’],[‘G’,’I’],[‘H’,’I’]]
Advertisement
Answer
This should do it. You have to flatten the result of combinations.
from itertools import combinations x = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] y = [list(combinations(xx, 2)) for xx in x] z = [list(item) for subl in y for item in subl] z [['A', 'B'], ['C', 'D'], ['C', 'E'], ['D', 'E'], ['F', 'G'], ['F', 'H'], ['F', 'I'], ['G', 'H'], ['G', 'I'], ['H', 'I']]