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.
JavaScript
x
18
18
1
from itertools import combinations
2
x = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']]
3
y = [list(combinations(xx, 2)) for xx in x]
4
z = [list(item) for subl in y for item in subl]
5
6
z
7
8
[['A', 'B'],
9
['C', 'D'],
10
['C', 'E'],
11
['D', 'E'],
12
['F', 'G'],
13
['F', 'H'],
14
['F', 'I'],
15
['G', 'H'],
16
['G', 'I'],
17
['H', 'I']]
18