循环可变长度的变量

时间:2012-11-15 03:40:00

标签: python loops for-loop

  

可能重复:
  Get the cartesian product of a series of lists in Python

假设我有一个长度为n的数组,表示n个变量,以及n个变量的函数f。我想总结f应用于某些有限集合中的n个变量的所有值(即{0,1})。从概念上讲,它会像

for x[1] in {0,1}:
  for x[2] in {0,1}:
     ... 
       sum += f(x[1], ..., x[n])

但显然你不能写这个。

有没有一种很好的方法来做到这一点,比如Python? (对于{0,1}中值的特定情况,我可以循环遍历从0到2 ^ n-1的整数的二进制表示,但我想要一个更通用的解决方案)。

1 个答案:

答案 0 :(得分:0)

# f is a function
# K is a list of possible values your variable may take
# n is number of args that f takes
import itertools

def sum_of_f_over_K_n(f,K,n):
    K_to_the_n = [K for i in xrange(n)]
    return sum(map(lambda(x):f(*x),itertools.product(*K_to_the_n)))

some_list = [0,1] # where your variables come from
def sample_func(a,b,c,d,e):
    return a or b or c or d or e
sum_of_f_over_K_n(sample_func, some_list, 5) == 2**5 -1