迭代Python中多个列表中的所有值组合 [英] Iterate over all combinations of values in multiple lists in Python

查看:705
本文介绍了迭代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]

然后我希望输出为:

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?

推荐答案

itertools.product 应该可以解决问题。

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

注意 itertools .product 返回一个迭代器,所以如果你只想迭代它一次就不需要将它转换成一个列表。

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.

如。

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

这篇关于迭代Python中多个列表中的所有值组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆