从子列表中的元素中获取所有对

时间:2016-10-03 15:42:32

标签: python

我有一份子列表。我需要子列表中元素之间的所有可能对。例如,对于这样的列表:

a=[[1,2,3],[4,5],[6]]

结果应为:

result=[[1,4], [1,5], [1,6], 
        [2,4], [2,5], [2,6], 
        [3,4], [3,5], [3,6], 
        [4,6], [5,6]]

列表(和子列表)具有各种随机长度。

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作

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

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

# 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