Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

iteration - Iterate over all combinations of values in multiple lists in Python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

itertools.product should do the trick.

>>> import itertools
>>> 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...