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

Generate combinations list from values in a list of tuples

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

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

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

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

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

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

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

下面会做,使用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))]

使用 itertools.product and itertools.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)

您可以使用:

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