我想为元组列表生成介于排列和组合之间的东西。例如,如果我有列表
list_of_tuples = [(1,20), (1,21), (2,18), (2,19)]
我想创建 3 个元组的所有可能“组合”,以便我希望列表包含结果 [(1,20), (1,20), (1,20)]
但我认为 [(1,20), (1,20), (1,21)]
与 [(1,20), (1,21), (1,20)]
和 [(1,21), (1,20), (1,20)]
并且只想保留其中一个(无关紧要)哪一个)。
换句话说,如果“组合”包含与另一个“组合”相同的元组,我不想保留另一个。
我试过类似的东西
list_of_lists = [list_of_tuples]*3
results = list(itertools.product(*list_of_lists))
results = set(results)
但是通过使用 set()
我失去了 [(1,20), (1,20), (1,20)]
和所有其他结果具有相同的元组三次。
最佳答案
使用itertools.combinations_with_replacement
,它应该完全符合您的描述:
>>> from itertools import combinations_with_replacement
>>> list_of_tuples = [(1,20), (1,21), (2,18), (2,19)]
>>> list(combinations_with_replacement(list_of_tuples, 3))
[((1, 20), (1, 20), (1, 20)),
((1, 20), (1, 20), (1, 21)),
((1, 20), (1, 20), (2, 18)),
((1, 20), (1, 20), (2, 19)),
((1, 20), (1, 21), (1, 21)),
((1, 20), (1, 21), (2, 18)),
((1, 20), (1, 21), (2, 19)),
((1, 20), (2, 18), (2, 18)),
((1, 20), (2, 18), (2, 19)),
((1, 20), (2, 19), (2, 19)),
((1, 21), (1, 21), (1, 21)),
((1, 21), (1, 21), (2, 18)),
((1, 21), (1, 21), (2, 19)),
((1, 21), (2, 18), (2, 18)),
((1, 21), (2, 18), (2, 19)),
((1, 21), (2, 19), (2, 19)),
((2, 18), (2, 18), (2, 18)),
((2, 18), (2, 18), (2, 19)),
((2, 18), (2, 19), (2, 19)),
((2, 19), (2, 19), (2, 19))]
关于python - 元组列表的唯一排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48402051/