简体   繁体   中英

List comprehension to create list of strings from two lists

I have two lists of strings and I want to use them to create a list of strings.

m1 = ["Ag", "Pt"]
m2 = ["Ir", "Mn"]
codes = []
for i in range (len (m1) ):
    codes.append('6%s@32%s' %(m1[i], m2[i] ) )
print codes

For example codes could have the elements ["6Ag@32Ir", "6Pt@32Mn"]

I want to turn the following into a list comprehension.

Non-zip method:

>>> m1 = ["Ag", "Pt"]
>>> m2 = ["Ir", "Mn"]
>>> ['6%s@32%s' %(m1[i], m2[i]) for i in range(min(len(m1), len(m2)))]
['6Ag@32Ir', '6Pt@32Mn']

Turn that into a generator:

>>> ('6%s@32%s' %(m1[i], m2[i]) for i in xrange(min(len(m1), len(m2))))

Python 2, you can do:

>>> ['6%s@32%s' % (x, y) for x, y in map(None, m1, m2)]
['6Ag@32Ir', '6Pt@32Mn']

Or, you do not even need to unpack the tuple:

>>> ['6%s@32%s' % t for t in map(None, m1, m2)]

You can simply zip them and print them like this

m1, m2 = ["Ag", "Pt"], ["Ir", "Mn"]
print ["6{}@32{}".format(*items) for items in zip(m1, m2)]
# ['6Ag@32Ir', '6Pt@32Mn']

Or, if you prefer map approach,

from itertools import starmap
print list(starmap("6{}@32{}".format, zip(m1, m2)))

Or

print [item for item in starmap("6{}@32{}".format, zip(m1, m2))]

You can use a list comprehension and zip :

>>> m1 = ["Ag", "Pt"]
>>> m2 = ["Ir", "Mn"]
>>> zip(m1, m2)  #  zip is used to pair-up the items in m1 and m2
[('Ag', 'Ir'), ('Pt', 'Mn')]
>>> ["6%s@32%s" % x for x in zip(m1, m2)]
['6Ag@32Ir', '6Pt@32Mn']
>>>

Note that if m1 and m2 can be large, you should use itertools.izip instead of zip (which, in Python 2.x, creates an unnecessary list). However, the lists in your example are small enough that this is not a problem.

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