[英]Calculate and store function outputs in Python 2.7?
我有這樣的代碼:
nList = [[[0,0,0],[100420,0,623400]],\
[[]],\
[[100043,1324000,123240]],\
[[0,0,543],[3002340,443000,34300],[334000,4043400,7342],[0,0,134020]]
import math
prevX, prevY, prevT = 0, 0, 0
#Entry point
for traceIndex in range(0, len(nList)):
print 'trace: ' + str(traceIndex+1)
trace = nList[traceIndex]
for pointIndex in range(0, len(trace)):
point = trace[pointIndex]
if len(point)>0:
tempX, tempY, tempT = point[0], point[1], point[2]
if pointIndex != 0:
#calculate time difference here
timeDiff = calculateTime (tempT,prevT)
基本上, nList
在每個\\
被調用的跟蹤之前都有子列表,每個跟蹤都有三個元素的點。 例如, nList[0][0]
產生跡線1,點1 = [0,0,0]
。 point=[x-coordinate, y-coordinate, time]
。 我計算了每條軌跡中每個點的timeDiff。 現在我需要總結不同痕跡的timeDiff並打印它們,以便:
trace: 1
623400
trace: 2
trace: 3
trace: 4
187393
nList由名為'trace'的子列表組成,每個'trace'具有一個或多個具有3個元素的點,[x,y,t]。 例如,trace1有2個點,使trace1point1 = [0,0,0]和trace1point2 = [100420,0,623400]。 timeDiff計算t2和t1之間的差異。 對於trace1,這將是(623400-0)。 跟蹤4與跡線1相比具有更多的點,timeDiff將用於單個trace4pointN,其中1=<N=<4
,(34300-543),(7342-34300)和(134020-7342)。 我想編寫一個程序,在每個跟蹤中占用所有timeDiff,並以產生上述輸出的方式對它們進行求和。
使用zip更容易解決這個問題,並直接在元素上迭代,以避免在變量中存儲太多內容。 根據您的示例輸出,您需要每個時間點之間的絕對差異:
traces = [[[0,0,0],[100420,0,623400]],\
[[]],\
[[100043,1324000,123240]],\
[[0,0,543],[3002340,443000,34300],[334000,4043400,7342],[0,0,134020]]]
TIME_INDEX = 2
traceCounter = 1
for trace in traces:
print "trace:", traceCounter
traceCounter += 1
if len(trace[0]) < 2:
#no coordinate in first element of trace, nothing to do
continue
#Zip takes several lists as arguments and returns list of lists with every 0th element in the 0th list, every 1st element in the 1st list etc.
timeStamps = zip(*trace)[TIME_INDEX]
sumOfTimeDiffs = sum([abs(y-x) for x, y in zip(timeStamps[:-1], timeStamps[1:])] )
if sumOfTimeDiffs > 0:
print sumOfTimeDiffs
輸出:
trace: 1
623400
trace: 2
trace: 3
trace: 4
187393
nList = [[[0,0,0],[100420,0,623400]],\
[[]],\
[[100043,1324000,123240]],\
[[0,0,543],[3002340,443000,34300],[334000,4043400,7342],[0,0,134020]]]
for trace in nList:
list1=list()
trace_index = nList.index(trace)
print "trace%d"%(trace_index+1)
if len(trace)>1:
for point in trace:
list1.append(point[2])
list2 = list1[1:]
list1.pop()
output = (abs(i2 - i1) for i2,i1 in zip(list2,list1))
print(sum(output))
這應該工作。 基本上我通過提取跡線每個點的時間來形成一個列表。 然后形成了相同的重復列表。 從一個列表中刪除第一個元素,從另一個列表中刪除最后一個 然后減去列表。 在結果列表中添加元素會給出輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.