簡體   English   中英

連接兩個長度不同的列表中的元素

[英]Concatenate elements in two lists with different length

(我確定這已經在某處得到回答,但是我確實找不到正確的問題。也許我不知道該練習的正確動詞?)

我有兩個清單:

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]

因為它沒有引入新的軟件包,但是該軟件包是最基本的(好吧,我不知道哪種方法更快,這可能是個人喜好問題)。

使用列表理解

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

使用itertools.product和list理解,

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

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

這稱為笛卡爾積:

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

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

只需使用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']
from itertools import product
map(' '.join, product(prefix, suffix))
# ['A a', 'A b', 'B a', 'B b', 'C a', 'C b']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM