2010-11-17 47 views
2

(蟒蛇)如何迭代一系列固定列表中的所有可能值?

,所以我有以下值&列表:

name = colour 
size = ['256', '512', '1024', '2048', '4096', '8192', '16384', '32768'] 
depth = ['8', '16', '32'] 
scalar = ['False', 'True'] 
alpha = ['False', 'True'] 
colour = app.Color(0.5) 

,我想遍歷這些生產具有以下結構的每一個可能的組合:

createChannel(ChannelInfo(name, size, depth, scalar, alpha, colour)) 

所以名稱,大小等的值必須保持在相同的位置,但是它們必須迭代所有可能的大小,深度等組合。

即我想要回這樣的事:

createChannel(ChannelInfo('colour', 256, 8, False, True, 0.5) 
createChannel(ChannelInfo('colour1', 256, 8, False, False, 0.5) 
createChannel(ChannelInfo('colour2', 256, 16, False, False, 0.5) 

...等等...有96個組合

感謝

+0

你的問題涉及到太多的東西是不相關的,你要解決的概念,你還沒有解釋。我建議你清理它並以可理解的方式呈現它。 – 2010-11-17 17:14:56

+0

你的意思是'name ='colour''? – martineau 2010-11-17 18:16:50

回答

0

最近我有同樣的要求。我借用了here這個跨產品功能。

def cross(*sequences): 
    # visualize an odometer, with "wheels" displaying "digits"...: 
    wheels = map(iter, sequences) 
    digits = [it.next() for it in wheels] 
    while True: 
     yield tuple(digits) 
     for i in range(len(digits)-1, -1, -1): 
      try: 
       digits[i] = wheels[i].next() 
       break 
      except StopIteration: 
       wheels[i] = iter(sequences[i]) 
       digits[i] = wheels[i].next() 
     else: 
      break 

將它傳遞給一組列表,它將返回一個生成器,它按照上面指定的方式迭代。

+0

從Python 2.6開始,在'intertools'模塊中有一個'product()'方法。 – martineau 2010-11-17 18:22:35

+0

是的,THC4k已經發布了答案。我在這裏留下了這個,因爲當我只訪問Python 2.5時發現它很有用。 – 2010-11-17 21:57:59

7
import itertools 
for iter in itertools.product(size, depth, scalar, alpha): 
    print iter # prints 96 four-element tuples 
+0

我發佈我的答案,而你張貼這個。我不知道itertools模塊。這比我的更好。 – Chris 2010-11-17 17:20:47

1
from itertools import product 

# generates all the possible values 
combinations = product(size, depth, scalar, alpha) 
# call the function for each combination 
# i guess `names` is a list of 96 names .. 
items = [createChannel(ChannelInfo(name, *row)) 
      for name, row in zip(names, combinations)] 
+0

我認爲有一個Python包做到了這一點。忘記我的解決方案。 – 2010-11-17 17:20:24