我有两个字符串列表,我想用它们来创建一个字符串列表。
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
例如代码可以包含[" 6Ag @ 32Ir"," 6Pt @ 32Mn"]
我想将以下内容转换为列表理解。
答案 0 :(得分:4)
非拉链方法:
>>> 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']
将其变成发电机:
>>> ('6%s@32%s' %(m1[i], m2[i]) for i in xrange(min(len(m1), len(m2))))
Python 2,你可以这样做:
>>> ['6%s@32%s' % (x, y) for x, y in map(None, m1, m2)]
['6Ag@32Ir', '6Pt@32Mn']
或者,您甚至不需要解压缩元组:
>>> ['6%s@32%s' % t for t in map(None, m1, m2)]
答案 1 :(得分:2)
你可以简单地zip
他们并按照这样打印
m1, m2 = ["Ag", "Pt"], ["Ir", "Mn"]
print ["6{}@32{}".format(*items) for items in zip(m1, m2)]
# ['6Ag@32Ir', '6Pt@32Mn']
或者,如果您更喜欢map
方法,
from itertools import starmap
print list(starmap("6{}@32{}".format, zip(m1, m2)))
或者
print [item for item in starmap("6{}@32{}".format, zip(m1, m2))]
答案 2 :(得分:1)
您可以使用list comprehension和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']
>>>
请注意,如果m1
和m2
可能很大,则应使用itertools.izip
而不是zip
(在Python 2.x中创建不必要的列表) 。但是,您的示例中的列表足够小,这不是问题。