python - 列表中不同元组的元素组合

标签 python tuples combinatorics

我有一个像这样的元组列表:[(1, 2, 3), (2, 4)](列表的长度和元组的长度可能会有所不同)我想要从列表中的每个元组中获取包含至少一个元素的所有组合,以及包含更多元素的那些组合。

所以这个例子中的结果应该是:
[[1, 2, 3, 2, 4], [1, 2, 2, 4], [2, 3, 2, 4], [1, 2, 4], [2, 2, 4 ], [3, 2, 4], [1, 2, 3, 2], [1, 2, 3, 4], [1, 2, 2], [1, 2, 4], [2, 3 , 2], [2, 3, 4], [1, 2], [1, 4], [2, 2], [2, 4], [3, 2], [3, 4]]

最小的结果应包含等于原始列表中元组数的元素数,最大的结果应包含元组中存在的所有元素。

元素的顺序无关紧要,最终应该消除重复项(因此 [1, 2, 3, 2, 4] = [1, 2, 3, 4] 并且应该是在结果中只有一次,类似 [3, 2] = [2, 3] 等),但我考虑在创建整个列表后排序和/或消除重复项。

最好的方法是什么?坦率地说,我什至不知道如何正确开始……

最佳答案

您需要 L 中各项的幂集的笛卡尔积 - 除非其中任何一项为空。一种方法是在构造幂集时只留下空元素。

from itertools import product, combinations, chain
L = [(1, 2, 3), (2, 4)]
def powerset(iterable):
    "powerset minus the empty element"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))

print [list(chain.from_iterable(c)) for c in product(*(powerset(x) for x in L))]

打印

[[1, 2], [1, 4], [1, 2, 4], [2, 2], [2, 4], [2, 2, 4], [3, 2], [3, 4], [3, 2, 4], [1, 2, 2], [1, 2, 4], [1, 2, 2, 4], [1, 3, 2], [1, 3, 4], [1, 3, 2, 4], [2, 3, 2], [2, 3, 4], [2, 3, 2, 4], [1, 2, 3, 2], [1, 2, 3, 4], [1, 2, 3, 2, 4]]

关于python - 列表中不同元组的元素组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22799053/

相关文章:

python - Flask SQLAlchemy order_by 关系

ArcGIS 10 中的 Python 脚本正在使用模块 re 并返回 "global name ' re' 未定义”

python - python 中的元组排序

algorithm - Matlab:找到产生另一个矩阵的置换矩阵

matlab - 在 Matlab 中随机选择所有可能组合的子集?

python - 在Python中证明傅里叶变换运算

python - 如何在 Django 中进行分层验证?

python - 无论元素顺序如何,获取列表中元组的数量

c++ - 只有 2 个元素的元组有性能损失吗?

math - 是否有函数 f(n) 返回 n :th combination in an ordered list of combinations without repetition?