我有两个列表,如: 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]]
我希望匹配每个子列表中的第一个元素,并对子列表中的第二个元素进行减法。我使用简单循环:
for i in 1:
for j in 2:
if i == j:
i[1] - j[1]
有一种快速的方法吗?
非常感谢!
答案 0 :(得分:1)
这就是你要找的东西:
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)]
答案 1 :(得分:0)
您的问题有点难以解释。也许一些预期的产出会产生不同。 但是,这就是我的解释。
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))
预期产出:[[113,2291.27],[114,-45.86000000000058],[116, 3083.8500000000004],[124,66.26999999999998],[127,572.12]]