繁体   English   中英

python中两个列表的笛卡尔积

[英]Cartesian product of two lists in python

python中两个列表的笛卡尔积

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

预期输出:

list3 = ['a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4', 'b5']

做一个列表理解,遍历两个列表并添加字符串,比如

list3 = [i+str(j) for i in list1 for j in list2]

如果您使用的是 Python 3.6+,则可以按如下方式使用 f-strings:

list3 = [f'{a}{b}' for a in list1 for b in list2]

我真的很喜欢这个符号,因为它非常易读并且与笛卡尔积的定义相匹配。

如果你想要更复杂的代码,你可以使用itertools.product

import itertools

list3 = [f'{a}{b}' for a, b in itertools.product(list1, list2)]

我检查了性能,似乎列表理解比itertools版本运行得更快。

您可以使用itertools.product功能:

from itertools import product

list3 = [a+str(b) for a, b in product(list1, list2)]

如果你不熟悉列表理解,你也可以使用

list3 = []
for l in list1:
    for b in list2:
        list3.append(l + b)
print list3

这将做同样的事情,但使用上面的列表理解将是最好的方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM