迭代 Python 中多个列表中的所有值组合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16384109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:27:13  来源:igfitidea点击:

Iterate over all combinations of values in multiple lists in Python

pythoniteration

提问by DurgaDatta

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 combinedlist. How do I get this done?

我想遍历组合列表。我如何完成这项工作?

采纳答案by Volatility

itertools.productshould do the trick.

itertools.product应该做的伎俩。

>>> 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.productreturns an iterator, so you don't need to convert it into a list if you are only going to iterate over it once.

请注意,itertools.product返回一个迭代器,因此如果您只打算对其进行一次迭代,则无需将其转换为列表。

eg.

例如。

for x in itertools.product([1, 5, 8], [0.5, 4]):
    # do stuff

回答by spinup

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