簡體   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