连接两个长度不同的列表中的元素

时间:2018-06-27 10:28:50

标签: python list concatenation

(我确定这已经在某个地方回答了,但我确实找不到正确的问题。也许我不知道该练习的正确动词?)

我有两个列表:

prefix = ['A', 'B', 'C']
suffix = ['a', 'b']

我想得到这个:

output = ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

我知道zip方法,该方法以加入的列表中最短的长度停止:

output_wrong = [p+' '+s for p,s in zip(prefix,suffix)]

那么最Python化的方式是什么?

编辑:

虽然大多数答案都喜欢itertools.product,但我却更喜欢这样:

output = [i + ' ' + j for i in prefix for j in suffix]

因为它没有引入新的软件包,但是该软件包是最基本的(好吧,我不知道哪种方法更快,这可能是个人喜好问题。)

7 个答案:

答案 0 :(得分:4)

使用列表理解

prefix = ['A', 'B', 'C']
suffix = ['a', 'b']
result = [val+" "+val2 for val in prefix for val2 in suffix ]
print(result)

输出

['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

答案 1 :(得分:3)

使用itertools.product和列表理解,

>>> [i + ' ' + j for i, j in product(prefix, suffix)]
# ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

答案 2 :(得分:2)

使用itertools.product

import itertools

prefix = ['A', 'B', 'C']
suffix = ['a', 'b']

print([f'{x} {y}' for x, y in itertools.product(prefix, suffix)])
# ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

答案 3 :(得分:1)

这称为笛卡尔积:

[p + ' ' + s for p, s in itertools.product(prefix, suffix)]

答案 4 :(得分:1)

使用product

In [33]: from itertools import product

In [34]: map(lambda x:' '.join(x),product(prefix,suffix))
Out[34]: ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

答案 5 :(得分:1)

只需使用list comprehension

prefix = ['A', 'B', 'C']
suffix = ['a', 'b']
output = [i+" "+j for i in prefix for j in suffix]
print(output)

输出:

['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

答案 6 :(得分:0)

from itertools import product
map(' '.join, product(prefix, suffix))
# ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']
相关问题