如何从一组列表中获取笛卡尔积(所有可能的值组合)?
输入:
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/