Get All Pairs From Elements In Sublists
I have a list of sublists. I need all possible pairs between the elements in the sublists. For example, for a list like this: a=[[1,2,3],[4,5],[6]] The result should be: result=
Solution 1:
You can do the following
>>> from itertools import chain
>>> a=[[1,2,3],[4,5],[6]]
>>> b=[]
>>> for index, item in enumerate(a):
... b.extend([[i, j] for i in item for j in chain.from_iterable(a[index+1:])])
>>> b
[[1, 4],
[1, 5],
[1, 6],
[2, 4],
[2, 5],
[2, 6],
[3, 4],
[3, 5],
[3, 6],
[4, 6],
[5, 6]]
Solution 2:
from itertools import chain, product, combinations
sublists = [[1, 2, 3], [4, 5], [6]]
pairs = chain.from_iterable(
product(*sublist_pair) for sublist_pair in combinations(sublists, 2)
)
for x, y in pairs:
print(x, y)
Solution 3:
# create an empty set to store unique sublist elements
initSet = set()
# combine all sublist elements
for sublist in a:
tempSet = set(sublist)
initSet = intiSet.union(tempSet)
initSet = list(initSet)
# find all possible non-repeating combinations
for _element in initSet:
combinations = list()
for i in range(1, len(initSet) - 1):
combinations.append([_element, initSet[i]]
initSet.pop(0)
#result stored in combinations
Post a Comment for "Get All Pairs From Elements In Sublists"