How to concatenate element-wise two lists in Python
I have two lists and I want to concatenate them element-wise. One of the list is subjected to string-formatting before concatenation.
For example :
a = [0, 1, 5, 6, 10, 11]
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']
In this case, a
is subjected to string-formatting. That is, new a
or aa
should be :
aa = [00, 01, 05, 06, 10, 11]
Final output should be :
c = ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
Can somebody please tell me how to do that?
Solution 1:
Use zip
:
>>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
Solution 2:
Using zip
[m+str(n) for m,n in zip(b,a)]
output
['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']
Solution 3:
Other solution (preferring printf formating style over .format()
usage), it's also smaller:
>>> ["%s%02d" % t for t in zip(b, a)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
Solution 4:
Than can be done elegantly with map and zip:
map(lambda (x,y): x+y, zip(list1, list2))
Example:
In [1]: map(lambda (x,y): x+y, zip([1,2,3,4],[4,5,6,7]))
Out[1]: [5, 7, 9, 11]