从列表python中生成值的组合

时间:2018-05-07 02:35:57

标签: python

我想获得列表列表的组合,例如

[['a0', 'a1'], ['b0', 'b1'], ['c0', 'c1', 'c2']]

我可以使用list(itertools.product(*listOfTuples))并获取

[('a0', 'b0', 'c0'), ('a0', 'b0', 'c1'), ('a0', 'b0', 'c2')... ('a1', 'b1', 'c2')]

如何获得长度为2的可能组合的列表?例如:

[('a0', 'b0'), ('a0', 'c0'), ('b0', 'c0')...

2 个答案:

答案 0 :(得分:1)

您可以展平列表,并创建一个简单的递归函数(对于在子列表中没有重复的结果):

d = [['a0', 'a1'], ['b0', 'b1'], ['c0', 'c1', 'c2']]
def combinations(d, current = []):
  if len(current) == 2:
    yield current
  else:
    for i in d:
      if i not in current:
        yield from combinations(d, current+[i])

print(list(combinations([i for b in d for i in b]))

输出:

[['a0', 'a1'], ['a0', 'b0'], ['a0', 'b1'], ['a0', 'c0'], ['a0', 'c1'], ['a0', 'c2'], ['a1', 'a0'], ['a1', 'b0'], ['a1', 'b1'], ['a1', 'c0'], ['a1', 'c1'], ['a1', 'c2'], ['b0', 'a0'], ['b0', 'a1'], ['b0', 'b1'], ['b0', 'c0'], ['b0', 'c1'], ['b0', 'c2'], ['b1', 'a0'], ['b1', 'a1'], ['b1', 'b0'], ['b1', 'c0'], ['b1', 'c1'], ['b1', 'c2'], ['c0', 'a0'], ['c0', 'a1'], ['c0', 'b0'], ['c0', 'b1'], ['c0', 'c1'], ['c0', 'c2'], ['c1', 'a0'], ['c1', 'a1'], ['c1', 'b0'], ['c1', 'b1'], ['c1', 'c0'], ['c1', 'c2'], ['c2', 'a0'], ['c2', 'a1'], ['c2', 'b0'], ['c2', 'b1'], ['c2', 'c0'], ['c2', 'c1']]

答案 1 :(得分:1)

您可以使用itertools.combinations()拨打r=2以获取每个三元组的所有对,然后展平,例如:

In []:
import itertools as it
[t for x in it.product(*s) for t in it.combinations(x, r=2)]

Out[]:
[('a0', 'b0'), ('a0', 'c0'), ('b0', 'c0'), ('a0', 'b0'), ('a0', 'c1'), ('b0', 'c1'),
 ('a0', 'b0'), ('a0', 'c2'), ('b0', 'c2'), ('a0', 'b1'), ('a0', 'c0'), ('b1', 'c0'), 
 ('a0', 'b1'), ('a0', 'c1'), ('b1', 'c1'), ('a0', 'b1'), ('a0', 'c2'), ('b1', 'c2'), 
 ('a1', 'b0'), ('a1', 'c0'), ('b0', 'c0'), ('a1', 'b0'), ('a1', 'c1'), ('b0', 'c1'), 
 ('a1', 'b0'), ('a1', 'c2'), ('b0', 'c2'), ('a1', 'b1'), ('a1', 'c0'), ('b1', 'c0'), 
 ('a1', 'b1'), ('a1', 'c1'), ('b1', 'c1'), ('a1', 'b1'), ('a1', 'c2'), ('b1', 'c2')]

但是,这会有重复,因为('a0', 'b0', 'c0')('a0', 'b0', 'c1')('a0', 'b0', 'c2')都会生成('a0', 'b0'),所以如果你想删除,那么你可以使用{{ 1}},但你失去了秩序:

set

对它进行排序确实将其按顺序排列:

In []:
{t for x in it.product(*s) for t in it.combinations(x, r=2)}

Out[]:
{('a1', 'c0'), ('b0', 'c1'), ('b0', 'c2'), ('a0', 'c1'), ('a0', 'c2'), ('b1', 'c1'), 
 ('b1', 'c2'), ('a1', 'b1'), ('a1', 'c1'), ('a1', 'c2'), ('b0', 'c0'), ('a0', 'c0'), 
 ('a1', 'b0'), ('b1', 'c0'), ('a0', 'b1'), ('a0', 'b0')}