简体   繁体   English

从元组列表中的值生成组合列表

[英]Generate combinations list from values in a list of tuples

I have a list of tuples, which essentially are ranges my ith value can iterate in. The list looks like the one below:我有一个元组列表,它们本质上是我的第 i 个值可以迭代的范围。该列表如下所示:

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

These are the upper and lower bounds of these ranges and will be fixed before generating all values where the bounds are inclusive.这些是这些范围的上限和下限,将在生成包含边界的所有值之前固定。

Can someone tell me what is the best way to generate unique combination where each value of the list lies between its tuple bounds?有人可以告诉我生成唯一组合的最佳方法是什么,其中列表的每个值都位于其元组边界之间? 14641 combinations. 14641 种组合。

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

I tried using for loops by nesting them but ran into issues with runtime.我尝试通过嵌套它们来使用 for 循环,但遇到了运行时问题。

Any help is appreciated.任何帮助表示赞赏。 Thanks a lot.非常感谢。

The following will do, using itertools.product :使用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)
# ...

If you need them in a list , just unpack the iterator:如果您需要在list中使用它们,只需解压迭代器:

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

Use itertools.product and itertools.starmap to map range over the intervals.使用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)

You could use:你可以使用:

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))

Getting random values:获取随机值:

import random
random.sample(all_products, 10)

output:输出:

[(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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM