如何获取元组列表序列

时间:2019-06-25 10:26:41

标签: arrays python-3.x combinations permutation

鉴于此为输入

[(A,1),(A,2),(B,0),(C,2),(C,3)]

输出应为:

[[(A,1),(B,0),(C,2)],[(A,2),(B,0),(C,2)],[(A,1),(B,0),(C,3)],[(A,2),(B,0),(C,3)]]

及其排列

1 个答案:

答案 0 :(得分:0)

尝试使用groupbyproduct

from itertools import groupby, product

input = [("A", 1), ("A", 2), ("B", 0), ("C", 2), ("C", 3)]

groups = groupby(input, key=lambda x: x[0])

output = [list(p) for p in product(*[item for item in (list(i) for g, i in groups)])]

print(output)

输出:

  

[[((A',1),('B',0),('C',2)],[('A',1),('B',0),('C ',3)],[('A',2),('B',0),('C',2)],[('A',2),('B',0),( 'C',3)]]