2012-11-15 225 views
0

可能重复的可变长度数:
Get the cartesian product of a series of lists in Python循环的变量

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

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的整数的二进制表示,但我想要一个更一般的解决方案)。

+2

你想要笛卡尔产品;看到[这个问题](http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python)之间的许多重复 - 难的部分是知道搜索什么词组。一旦你有了这些值,你可以用'f(* some_tuple)'将这些值提供给函数。 – DSM

+0

看起来你想要一个笛卡尔产品。查找['itertools.product'](http://docs.python.org/2/library/itertools.html) – inspectorG4dget

回答

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