如何使用自身计算列表的笛卡尔积 [英] How to calculate a Cartesian product of a list with itself

查看:179
本文介绍了如何使用自身计算列表的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

list = [0, 1, 2]

我想要所有可能的2种组合的列表:

I want a list of all possible 2-combinations:

combinations = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)]

在我看来,Python的itertools中的所有工具仅使(1,0)和(0,1)之一,而不是两者,我需要两者.除了手动输入以外,还有其他建议吗?

It seems to me that all the tools in itertools in Python only make one of (1,0) and (0,1), not both, I need both. Any suggestions, other than entering them by hand?

推荐答案

您正在寻找列表本身的笛卡尔积,而不是排列或组合.因此,您应该将itertools.productrepeat=2一起使用:

You are looking for a Cartesian product of that list with itself, not a permutation nor a combination. Therefore you should use itertools.product with repeat=2:

from itertools import product

li = [0, 1, 2]
print(list(product(li, repeat=2)))
>> [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

这篇关于如何使用自身计算列表的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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