python - 得到一系列列表的笛卡尔积?

如何从一组列表中获取笛卡尔积(所有可能的值组合)?

输入:

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

期望的输出:

[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), ...]

这种技术的一个常见应用是避免深度嵌套循环。见 Avoiding nested for loops更具体的副本。

如果您想要多次相同列表的笛卡尔积,itertools.product 可以优雅地处理。见 Operation on every pair of element in a list或 Generating permutations with repetitions .

最佳答案

itertools.product

可从 Python 2.6 获得。

import itertools

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
for element in itertools.product(*somelists):
    print(element)

与,

for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
    print(element)

https://stackoverflow.com/questions/533905/

相关文章:

python - PEP8 的 E128 : continuation line under-ind

python - 将标准输出重定向到 Python 中的文件?

python - 从 Django QuerySet 获取 SQL

python - 如何计算 ndarray 中某个项目的出现次数?

python - 为什么 'x' 中的 ('x' 比 'x' == 'x' 快?

python - 默认字典的默认字典?

python - 在 Python 3 中从 Web 下载文件

python - 测试 Python 中是否存在可执行文件?

python - 如何在 Python 中获取当前模块中所有类的列表?

python - 如何将 time.struct_time 对象转换为 datetime 对象?