Python,如何计算列表之间的差异

问题描述 投票:0回答:4

我有清单

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

并且需要计算此列表中两个相邻点之间的差。

例如,(B-A),(C-B),(D-C)并获得此输出:

output = [(20, -2), (43, 7), (-70, 0)

有没有快速的方法?

python list difference
4个回答
1
投票

如果将邻居变成成对,这个问题就变得微不足道了。这是把戏。

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

firsts = a[:-1]  # a without the last element.
seconds = a[1:]  # a without the first element.
pairs = zip(firsts, seconds)

print(list(pairs))  # To understand how it works.

for (first, second) in pairs:
  # Here first would be e.g. ('A', 10, 7),
  # and second would be e.g. ('B', 30, 5)
  # You can handle the rest yourself.
  pass

0
投票

您可以使用列表理解:

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

result = [ (second - a[i+1][1], third - a[i+1][2] )   for i, (first, second, third) in enumerate(a[:-1]) ]
print(result)

0
投票
for i,x in enumerate(a[:-1]):
    output.append((a[i+1][1]-a[i][1],a[i+1][2]-a[i][2]))


0
投票

使用列表理解]的可能解决方案可能是:

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]
diff = [ (a[i+1][1] - a[i][1], a[i+1][2] - a[i][2]) for i in range(len(a)-1)]
print(diff)
© www.soinside.com 2019 - 2024. All rights reserved.