python - 如何获得多个列表的笛卡尔积

标签 python list cartesian-product

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

例如,给定

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以获得更具体的副本。类似地,该技术可用于“分解”具有列表值的字典;请参阅Combine Python Dictionary Permutations into List of Dictionaries .

如果您想要多次相同列表与其自身的笛卡尔积,itertools.product可以优雅地处理这个问题。请参阅Operation on every pair of element in a listHow can I get "permutations with repetitions" from a list (Cartesian product of a list with itself)? .

许多已经了解 itertools.product 的人都在苦苦挣扎,因为它需要为每个输入序列提供单独的参数,而不是例如列表的列表。接受的答案显示了如何使用 * 处理此问题。但是,此处使用 * 来解包参数与在函数调用中使用它的任何其他时间根本上没有什么不同。请参阅Expanding tuples into arguments对于这个主题(并根据需要使用它来关闭重复的问题)。

最佳答案

使用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)

关于python - 如何获得多个列表的笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56302731/

相关文章:

java - 在 HashMap 列表中搜索键值对

c# - 有做笛卡尔积的好 LINQ 方法吗?

python - DataFrame 列的笛卡尔积并在 Python 中将新创建的行设置为 0

python - 修改 Python 3.1 中的特定数组元素

c# - 生成所有可能的组合

python - 如何阻止 Vim 突出显示 python 文件中的尾随空格

python - 用双引号Python获取str repr

python - 从外部停止正在运行的 while 循环

python - 如何在 .csv 文件中转义字符串 Python 2.7 中的逗号

r - 将不同长度的字符向量列表放入数据框中