如何加速在Python中创建所有可能的组合?

时间:2017-11-09 16:31:49

标签: python itertools

我试图从两个列表中生成所有可能的组合,如下所示:

import itertools

products = ['productA', 'productB', 'productC','productD']
suppliers = ['supplier1', 'supplier2', 'supplier3', 'supplier4']

allPossibleSupplies = [zip(products, s) for s in itertools.product(suppliers, repeat=len(products))]

for i , val in enumerate(allPossibleSupplies):
    print (i, val)

此示例中的输出将是255个唯一组合(产品,供应商):

(0, [('productA', 'supplier1'), ('productB', 'supplier1'), ('productC', 'supplier1'), ('productD', 'supplier1')])
....
....

我的问题:是否有更快的方法可以在更短的时间内生成相同的结果?当产品或供应商的数量增加时,这种方式是耗时的。

1 个答案:

答案 0 :(得分:0)

你必须itertool.product两个元素列表 然后,我建议将值存储在映射supplier index --> tuple(product, supplier)而不是列表

import itertools

products = ['productA', 'productB', 'productC','productD']
suppliers = ['supplier1', 'supplier2', 'supplier3', 'supplier4']

product_keys = {prod: idx for idx, prod in enumerate(products)}
allPossibleSupplies = {}

for elt in itertools.product(products, suppliers):  #<-- here, feed both lists to itertools.product
    try:
        allPossibleSupplies[product_keys[elt[0]]].append(elt)
    except KeyError:
        allPossibleSupplies[product_keys[elt[0]]] = [elt]

allPossibleSupplies

输出:

{0: [('productA', 'supplier1'),
  ('productA', 'supplier2'),
  ('productA', 'supplier3'),
  ('productA', 'supplier4')],
 1: [('productB', 'supplier1'),
  ('productB', 'supplier2'),
  ('productB', 'supplier3'),
  ('productB', 'supplier4')],
 2: [('productC', 'supplier1'),
  ('productC', 'supplier2'),
  ('productC', 'supplier3'),
  ('productC', 'supplier4')],
 3: [('productD', 'supplier1'),
  ('productD', 'supplier2'),
  ('productD', 'supplier3'),
  ('productD', 'supplier4')]}