我有以下两个清单:
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)
答案 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))