2012-11-15 220 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