2013-10-24 71 views
16

我有两个列表,我想将它们按元素进行连接。串联之前,其中一个列表要经过字符串格式化。如何在Python中连接元素明智的两个列表?

例如:

a = [0, 1, 5, 6, 10, 11] 
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2'] 

在这种情况下,a进行串格式化。也就是说,新的aaa应该是:

aa = [00, 01, 05, 06, 10, 11] 

最终输出应该是:

c = ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211'] 

有人可以告诉我该怎么做?

+0

尝试使用['zip'](http://docs.python.org/2/library/functions.html#zip)和['string.format'](http:// docs。 python.org/2/library/string.html#format-specification-mini-language) –

+0

@FrancescoMontesano谢谢,由nightcracker回答工作正常! – Sanchit

+0

@ nightcracker谢谢你的答案。是的,当然。但是,我现在无法接受你的答案。它显示要等待5分钟。那么,我会这样做:) – Sanchit

回答

18

使用zip

>>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)] 
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211'] 
+2

@downvoter - 谨慎解释为什么我的回答没有用? – orlp

+0

不是downvoter,只是旁观者,但你为什么要在“一个语句”中进行字符串连接和字符串格式化?为什么不只是'“{} {}”。格式(b_,a_)'? – dmedvinsky

+0

@dmedvinsky绝对没有理由,让我编辑 - 谢谢你的建议。 – orlp

0

比可以优雅地图和zip来完成:

map(lambda (x,y): x+y, zip(list1, list2)) 

例子:

In [1]: map(lambda (x,y): x+y, zip([1,2,3,4],[4,5,6,7])) 
Out[1]: [5, 7, 9, 11] 
+0

它不会做什么OP要求 –

+2

不,但它是一般模式,我认为这是更重要的。 –

1

不使用拉链。我不知道,我认为这是明显的做法。也许我只是学会了C第一:)

c=[] 
for i in xrange(len(a)): 
    c.append("%s%02d" % (b[i],a[i])) 
7

使用Zip

[m+str(n) for m,n in zip(b,a)] 

输出

['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211'] 
1
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2'] 
aa = [0, 1, 5, 6, 10, 11] 
new_list =[] 
if len(aa) != len(b): 
    print 'list length mismatch' 
else: 
    for each in range(0,len(aa)): 
     new_list.append(b[each] + str(aa[each])) 
print new_list 
5

其他解决方案(宁愿printf的格式化风格在.format()使用),它是也更小:

>>> ["%s%02d" % t for t in zip(b, a)] 
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211'] 
相关问题