多个字符串列表在一起

时间:2015-07-19 05:05:27

标签: python list matrix

我有以下两个清单:

Sites = ["iTunes","Google"]
PurchaseTypes = ["Rental","Purchase"]

我如何将所有组合相乘,从而产生:

[
    "iTunesRental",
    "iTunesPurchase",
    "GoogleRental",
    "GooglePurchase"
]

是否有python操作来执行此操作?或者是否需要为每个列表执行for循环?那就是:

combined = []
for s in sites:
    for pt in purchase_types:
        combined.append(s+pt)

3 个答案:

答案 0 :(得分:4)

使用列表理解:

>>> [a + b for a in Sites for b in PurchaseTypes]
['iTunesRental', 'iTunesPurchase', 'GoogleRental', 'GooglePurchase']

答案 1 :(得分:1)

您可以使用itertools.product() -

>>> Sites = [
...         "iTunes",
...         "Google"
...     ]
>>>
>>>
>>> PurchaseTypes = [
...         "Rental",
...         "Purchase"
...     ]
>>>
>>> from itertools import product
>>> l = ['{}{}'.format(*i) for i in product(Sites,PurchaseTypes)]
>>> l
['iTunesRental', 'iTunesPurchase', 'GoogleRental', 'GooglePurchase']

答案 2 :(得分:0)

你可以去map-reduce lambda操作。 Map-reduce操作比列表推导慢。但这又是Pythonic编程风格之一。

在您的情况下,可以按如下方式完成:

combined = reduce(lambda a,b:a+b,map(lambda x:map(lambda y:x+y,Sites),PurchaseTypes))