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

时间:2010-11-17 17:10:44

标签: python

(蟒)

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

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种组合

由于

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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)]

答案 2 :(得分: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

传递一组列表,它将返回一个生成器,它按照你上面的指定进行迭代。