Iterate over all combinations of values in multipl

2019-01-08 16:45发布

Given multiple list of possibly varying length, I want to iterate over all combinations of values, one item from each list. For example:

first = [1, 5, 8]
second = [0.5, 4]

Then I want the output of to be:

combined = [(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]

I want to iterate over the combined list. How do I get this done?

2条回答
乱世女痞
2楼-- · 2019-01-08 16:58

itertools.product should do the trick.

>>> list(itertools.product([1, 5, 8], [0.5, 4]))
[(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]

Note that itertools.product returns an iterator, so you don't need to convert it into a list if you are only going to iterate over it once.

eg.

for x in itertools.product([1, 5, 8], [0.5, 4]):
    # do stuff
查看更多
Lonely孤独者°
3楼-- · 2019-01-08 17:12

This can be achieved without any imports using a list comprehension. Using your example:

first = [1, 5, 8]
second = [0.5, 4]

combined = [(f,s) for f in first for s in second]

print(combined)
# [(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]
查看更多
登录 后发表回答