Python中两个列表的笛卡尔积

14

Python中两个列表的笛卡尔积

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

预期输出:

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

1
这个回答解决了你的问题吗?在Python中连接两个不同列表中的字符串 - Georgy
4个回答

15

做一个列表推导式,遍历这两个列表并将字符串相加,像这样:

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

10
如果你正在使用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版本运行得更快。

5
你可以使用 itertools.product 函数:
from itertools import product

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

1
如果您不熟悉列表推导式,您也可以使用。
list3 = []
for l in list1:
    for b in list2:
        list3.append(l + b)
print list3

这将执行完全相同的操作,但使用上面的列表推导式将是最好的方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接