[英]How to handle a variable number of nested for loops?
I have a dict for which I would like to find all combinations of sums of values, multiplied by an increasing factor. 我有一个字典,我想找到所有值总和的组合,再乘以一个递增因子。 A possible code for the case where the size of the dict is 2:
字典大小为2的情况下的可能代码:
# data and n come from elsewhere
data = {'a': 1, 'b': 2}
n = 3
for x in xrange(0, n):
for y in xrange(0, n):
print("{0} * {1} + {2} * {3} = {4}".format(x, data['a'], y, data['b'], x * data['a'] + y * data['b']))
which gives 这使
0 * 1 + 0 * 2 = 0
0 * 1 + 1 * 2 = 2
0 * 1 + 2 * 2 = 4
1 * 1 + 0 * 2 = 1
(...)
2 * 1 + 2 * 2 = 6
The problem I have is that the number of elements in the dict will vary, so the number of nested for
should be changing as well. 我的问题是,元件的在字典数量将有所不同,所以嵌套数
for
应改变为好。 Is there a better way to code such a problem to accommodate such a variable dict? 有没有更好的方法来编码这样的问题以适应这样的可变字典?
You can replace your nested loop with a single loop over the cartesian product 您可以用笛卡尔积上的单个循环替换嵌套循环
from itertools import product
for x, y in product(range(n), repeat=2):
...
This isn't too useful in itself as you still hardcode 2 variables in there. 它本身并不太有用,因为您仍然在其中硬编码2个变量。 But it leads us on the the next point -
itertools.product
yields tuples as you iterate over it 但这将我们引向了下一点
itertools.product
在您对其进行迭代时会生成元组
from itertools import product
num_loops = 5 # len(data) in your case
for item in product(range(n), repeat=num_loops):
... # item is a 5-tuple
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.