Reputation: 236
I have 2 two lists like: 1:
[[113, 3528.27], [114, 4376.139999999999], [116, 4328.85], [124, 390.27], [127, 814.12]]
2:
[[113, 1237], [114, 4422], [116, 1245], [124, 324], [127, 242]]
I want to match the first element in each sublist, and do subtraction for the second element in the sublist. I used simple loop as:
for i in 1:
for j in 2:
if i == j:
i[1] - j[1]
is there a fast way to make it?
Thanks a lot!
Upvotes: 0
Views: 42
Reputation: 27869
Is this what you were looking for:
a = [[113, 3528.27], [114, 4376.139999999999], [116, 4328.85], [124, 390.27], [127, 814.12]]
b = [[113, 1237], [114, 4422], [116, 1245], [124, 324], [127, 242]]
c = [[x[0], x[1] - y[1]] for x, y in zip(a, b)]
Upvotes: 1
Reputation: 1298
Your question is a bit hard to interpret. Maybe some expected output would have made the difference. However, this is what I interpreted it to mean.
def sub_two_lists(list1, list2):
sublist = []
mainlist = []
for i in list1:
for j in list2:
if i[0] == j[0]:
sublist.append(i[0])
susblist.append(i[1] - j[1])
mainlist.append(sublist)
sublist = []
return mainlist
list1 = [[113, 3528.27], [114, 4376.139999999999], [116, 4328.85], [124, 390.27], [127, 814.12]]
list2 = [[113, 1237], [114, 4422], [116, 1245], [124, 324], [127, 242]]
print(sub_two_lists(list1, list2))
Expected output: [[113, 2291.27], [114, -45.86000000000058], [116, 3083.8500000000004], [124, 66.26999999999998], [127, 572.12]]
Upvotes: 0