开发者

How do I iterate through all possible values in a series of fixed lists?

开发者 https://www.devze.com 2023-01-26 02:39 出处:网络
(python) so I have the following values & lists: name = colour size = [\'256\', \'512\', \'1024\', \'2048\', \'4096\', \'8192\', \'16384\', \'32768\']

(python)

so I have the following values & lists:

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)

and I want to iterate over these to produce every possible combination with the following structure:

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

so the values for name, size, etc must stay in the same place, but they must iterate over all possible combinations of size, depth, etc..

i.e. I want to return something like this:

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)
开发者_运维技巧

...etc...there are 96 combinations

Thanks


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


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)]


I recently had the same requirement. I borrowed this cross-product function from 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

Pass it a set of lists and it will return a generator which iterates as you specified above.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号