【问题标题】:Generate combinations list from values in a list of tuples从元组列表中的值生成组合列表
【发布时间】:2021-10-13 16:09:24
【问题描述】:

我有一个元组列表,本质上是我的第 i 个值可以迭代的范围。 该列表如下所示:

L = [(10,20),(30,40),(60,70),(90,100)]

这些是这些范围的上限和下限,将在生成包含边界的所有值之前固定。

有人能告诉我,在列表的每个值都位于其元组边界之间的情况下,生成唯一组合的最佳方法是什么? 14641种组合。

Ex: 
[15,30,65,90] is valid
[27,33,67,99] is not valid

我尝试通过嵌套使用 for 循环,但遇到了运行时问题。

感谢任何帮助。 非常感谢。

【问题讨论】:

  • 将元组转换为范围,然后使用itertools.product
  • 所有组合还是随机一种?上限是包含还是排除?
  • 嗨,我需要所有的组合,是的,边界是包容性的。

标签: python list loops combinations permutation


【解决方案1】:

使用itertools.product

from itertools import product

combos = product(*(range(a, b+1) for a, b in L))
next(combos)
# (10, 30, 60, 90)
next(combos)
# (10, 30, 60, 91)
# ...

如果您在 list 中需要它们,只需解压缩迭代器即可:

combos = [*product(*(range(a, b+1) for a, b in L))]

【讨论】:

    【解决方案2】:

    使用itertools.productitertools.starmap 映射区间上的范围。

    from itertools import product, starmap
    
    L = [(10, 20), (30, 40), (60, 70), (90, 100)]
    
    Ls = [(lb, ub + 1) for lb, ub in L]
    for combination in product(*starmap(range, L)):
        print(combination)
    

    【讨论】:

      【解决方案3】:

      你可以使用:

      from itertools import product
      
      L = [(10,20),(30,40),(60,70),(90,100)]
      L2 = [list(range(a, b+1)) for a,b in L]
      
      all_products = list(itertools.product(*L2))
      

      获取随机值:

      import random
      random.sample(all_products, 10)
      

      输出:

      [(12, 37, 61, 98),
       (15, 35, 65, 90),
       (13, 38, 61, 98),
       (12, 37, 61, 92),
       (19, 34, 63, 91),
       (15, 37, 66, 91),
       (13, 32, 66, 98),
       (17, 31, 64, 97),
       (10, 38, 63, 99),
       (16, 34, 61, 90)]
      

      【讨论】:

      • 刚刚看到有边界包含的评论
      • @user2390182 这实际上很奇怪,因为最初的解释是总组合产生了 10k 个匹配排除上限的值
      • 没错,OP 一定算错了 :) 在所有编程中独占上限的主要原因之一:length = upper - lower!
      • @user2390182 我知道,这就是我默认排除的原因;)
      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多