首页 > 解决方案 > 连接两个不同长度的列表中的元素

问题描述

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

我有两个清单:

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)]

那么最Pythonic的方式是什么?

编辑:

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

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

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

标签: pythonlistconcatenation

解决方案


使用列表理解

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']

推荐阅读