python - 元组列表的唯一排列

标签 python combinatorics nested-lists

我想为元组列表生成介于排列和组合之间的东西。例如,如果我有列表

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/

相关文章:

python - 更改格式 sorl 缩略图

python - 如何将带有表情符号和特殊字符的国际字符串编码存储在数据库中

algorithm - 给定一组数字和元素相对位置的一些条件,生成一组排列

r - 从列表列表制作数据框,但每个元素都是一列

python - 如何复制嵌套列表中的元素?

python - 检查节点是否存在

python - TensorFlow:将 py_func 保存到 .pb 文件

java - 使用 Java 8 从(嵌套列表)列表列表中获取最大和最小总和的列表

matlab - 在 MATLAB 中查找总和为特定数字的向量元素

string - 如何生成多重集的所有排列?