[英]Generate combinations list from values in a list of tuples
我有一个元组列表,它们本质上是我的第 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
执行以下操作:
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
和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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.