简体   繁体   中英

Multiple list of strings together

I have the following two lists:

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

How would I multiply all combinations together, thus yielding:

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

Is there a python operation to do this? Or is it required to do a for loop for each list? That is:

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

Use list comprehension:

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

You can use 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']

You can go for map-reduce lambda operations. Map-reduce operations are slower than list-comprehensions. But again this is one of the styles of Pythonic programming.

In your case, it can be done as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM