how to get [(1, 2, 3, 4), (5, 6, 7, 8)] in my code using python
this is my code :
a = [(1,2),(5,6)]
b = [(3,4),(7,8)]
print zip(a,b)
and it show :
[((1, 2), (3, 4)), ((5开发者_开发技巧, 6), (7, 8))]
but i want get :
[(1, 2, 3, 4), (5, 6, 7, 8)]
so what can i do ,
thanks
Try this:
[aa+bb for aa,bb in zip(a,b)]
>>> a = [(1,2),(5,6)]
>>> b = [(3,4),(7,8)]
>>> [x+y for x,y in zip(a,b)]
[(1, 2, 3, 4), (5, 6, 7, 8)]
>>>
you can use the following list comprehension:
[x + y for (i, x) in enumerate(a) for (j, y) in enumerate(b) if i == j]
Result:
[(1, 2, 3, 4), (5, 6, 7, 8)]
Update #2
You can also use this list comprehension for your specific input:
[a[0] + b[0], a[1] + b[1]]
which is obviously faster than the zip
version.
from timeit import Timer
s1 = """\
a = [(1, 2), (5, 6)]
b = [(3, 4), (7, 8)]
[x + y for (i, x) in enumerate(a) for (j, y) in enumerate(b) if i == j]
"""
s2 = """\
a = [(1, 2), (5, 6)]
b = [(3, 4), (7, 8)]
[x + y for x, y in zip(a,b)]
"""
s3 = """\
a = [(1, 2), (5, 6)]
b = [(3, 4), (7, 8)]
[a[0] + b[0], a[1] + b[1]]
"""
t1 = Timer(s1)
t2 = Timer(s2)
t3 = Timer(s3)
print ("non-zip: {0} | zip: {1} | list-concat: {2}".format(t1.timeit(), t2.timeit(), t3.timeit()))
Results (Python 2.6.6 on Linux x86-64):
non-zip: 2.17631602287 | zip: 1.20438694954 | list-concat: 0.658749103546
精彩评论