首页 > 解决方案 > 以有效的方式组合项目列表

问题描述

我正在尝试使用一些 Python 科学库查找是否有更有效的方法来查找这些组合。

我试图避免本地for循环和列表追加,更喜欢使用一些 NumPy 或类似的功能,理论上应该更有效,因为它在后台使用 C 代码。我正在努力寻找一个,但对我来说,以一种有效的方式而不是使用缓慢的 Python 原生结构来进行这些操作是一个很常见的问题。

我想知道我是否在寻找错误的地方?例如,这在这里似乎没有帮助:https ://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.binomial.html

请参阅此处,我从下限 2 开始获取长度为 5 的列表的二项式系数,并找出所有可能的组合。同时,我追加到一个全局列表,这样我就可以从原始输入列表中获得一个很好的“已获取项目”列表。

import itertools

input_list = ['a', 'b', 'c', 'd', 'e']

minimum_amount = 2

comb_list = []
for i in range(minimum_amount, len(input_list)):
    curr_list = input_list[:i+1]
    print(f"the current index is: {i}, the lists are: {curr_list}")
    curr_comb_list = list(itertools.combinations(curr_list, i))
    comb_list = comb_list + curr_comb_list
print(f"found {len(comb_list)} combinations (check on set length: {len(set(comb_list))})")
print(comb_list)

给出:

found 12 combinations (check on set length: 12)
[('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c'), ('a', 'b', 'd'), 
('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd'), ('a', 'b', 'c', 'e'), 
('a', 'b', 'd', 'e'), ('a', 'c', 'd', 'e'), ('b', 'c', 'd', 'e')]

标签: pythonnumpycombinationsbinomial-coefficients

解决方案


最终列表包含从 1 到 任意长度的所有组合len(input_list),这实际上是Power Set
查看如何获取列表元素的所有可能组合?.


推荐阅读