How can I compute elements from two different lists in python?
I have two lists of ints, a开发者_如何学Gond I want systematically operate their objects. For example I have:
A = [ a1, a2, a3, a4 ...]
B = [ b1, b2, b3 ...]
and I want to print something like this:
a1+b1 a2
a2+b2 a3
a3+b3 a4
I think there are a "for loop" way, but I don't know how use two variables in a "for loop".
You could use zip
:
>>> A = ['a1', 'a2', 'a3', 'a4']
>>> B = ['b1', 'b2', 'b3']
>>> zip(A[:3], B, A[1:])
[('a1', 'b1', 'a2'), ('a2', 'b2', 'a3'), ('a3', 'b3', 'a4')]
>>> for a, b, c in zip(A[:3], B, A[1:]):
... print a + '+' + b + ' ' + c
...
a1+b1 a2
a2+b2 a3
a3+b3 a4
Are you looking for something simple like this:
In []: A= [1, 2, 3, 4]
In []: B= [1, 2, 3]
In []: for k, b in enumerate(B):
..: print A[k]+ b, A[k+ 1]
..:
2 2
4 3
6 4
Or perhaps something like this:
In []: for k, b in enumerate(B):
..: print '{}+{}\t{}'.format(A[k], b, A[k+ 1])
..:
1+1 2
2+2 3
3+3 4
With the pairwise
recipe from itertools
:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
a = [1,2,3,4]
b = [7,8,9]
for (a1, a2), b1 in izip(pairwise(a), b):
print a1 + b1, a2
for i,b in enumerate(B):
print(A[i] + '+' + b + '\t' + A[i+1])
[(a + b, c) for (a, b, c) in zip(A, B, A[1:])]
whatever A and B contain
This one
l = zip(map(sum, zip(A, B)), A[1:])
would produce a list of tuples of
[(a_1 + b_1, a_2), (a_2 + b_2, a_2), ..., (a_(i-1) + b_(i-1), a_i)]
To print it,
for a, b in l:
print a, b
精彩评论