Reputation: 185
I have these lists:
list1 = [3, 5, 2, 1, 9]
list2 = [6, 9, 1, 2, 4]
list3 = []
list4 = []
and I want to pass these formula:
x = a/b
y = 1/b
in which a is every value in list1 and b is every value in list2 and append the result of calculations into two empty lists - list3 and list4.
This is what I have but it's a disaster haha :(
u = 0
while u<len(list1):
for a in list1:
for b in list2:
x = a/b
y = 1/b
u+=1
list3.append(x,)
list4.append(y,)
Anyone can help me with this?
Upvotes: 2
Views: 19248
Reputation: 1
list3 = map((lambda x, y: x/y), list1, list2)
list4 = map(lambda x: 1/x), list2)
OR:
list3, list4 = zip(*map((lambda x, y: (x/y, 1/y)), list1, list2)
Upvotes: 0
Reputation: 13410
Here is a oneliner:
>>> list3,list4 = zip(*[(a/b,1/b) for a,b in zip(list1,list2)])
>>> list3
(0, 0, 2, 0, 2)
>>> list4
(0, 0, 1, 0, 0)
The output are tuples
. But they can be easily converted to list
.
Oh. It may be made even more memory efficient by using generator expression
instead of list comprehension
:
>>> zip(*((a/b,1/b) for a,b in zip(list1,list2)))
Upvotes: 9
Reputation: 375504
for a, b in zip(list1, list2):
x = a/b
y = 1/b
list3.append(x)
list4.append(y)
This is assuming you meant you wanted to use the lists pair-wise. If instead you meant you wanted every possible pairing of the lists, then:
for a in list1:
for b in list2:
x = a/b
y = 1/b
list3.append(x)
list4.append(y)
Upvotes: 5
Reputation: 41428
Just use the zip function in Python:
for a, b in zip(list1, list2):
list3.append(a/b)
list4.append(1/b)
Upvotes: 4
Reputation: 33223
for a,b in zip(list1,list2):
x = a/b
y = 1/b
?? something like this
Upvotes: 4