以有效的方式组合项目列表

2024-06-02 07:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到是否有一种更有效的方法来使用Python科学库查找这些组合

我试图避免原生的for循环和list append,我更喜欢使用一些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')]
  • 有没有可能避免for循环并使用一些科学库更快地完成这项工作
  • 我怎样才能更快地做到这一点

Tags: numpy列表forinputlen科学amountlist
2条回答

最后一个列表包含从1到len(input_list)的任何长度的所有组合,实际上是Power Set
看看How to get all possible combinations of a list’s elements?

您需要长度2或更多的输入列表中的所有组合

要获取它们,您可以运行:

comb_lst = list(itertools.chain.from_iterable(
    [ itertools.combinations(input_list, i)
        for i in range(2, len(input_list)) ]))

类似于itertools网站示例中的powerset, 但不完全相同(长度从2开始,而不是从1开始)

还要注意,代码中的curr\u list实际上仅用于打印

相关问题 更多 >