繁体   English   中英

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

[英]Python, how to calculate the difference between lists

我有清单

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

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

例如,(BA), (CB), (DC) 得到这个 output:

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

有什么快速的方法吗?

如果你把邻居变成一对,这个问题就变得微不足道了。 这就是诀窍

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)

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.
  print('first:', first, 'second:', second)  # To understand how it works.
  pass

您可以使用列表理解:

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)
for i,x in enumerate(a[:-1]):
    output.append((a[i+1][1]-a[i][1],a[i+1][2]-a[i][2]))

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

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]
output = [ (a[i+1][1] - a[i][1], a[i+1][2] - a[i][2]) for i in range(len(a)-1) ]
print(output)

如果你不想假设任何关于长度的事情

i=0
index=0
while i<len(a)-1:
    for ValueA in a[i]:
        if str(ValueA).isdigit():
            print(str(a[i+1][index])+" "+str(ValueA))
        index+=1
    i+=1
    index=0
from operator import sub
a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]
for i in range(len(a)-1):
    print(tuple(map(sub, a[i+1][1:],a[i][1:])))

尝试这个。 还向我们展示您的尝试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM