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?
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)))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With