python中两个列表中重叠值的平均值

时间:2018-05-05 12:30:13

标签: python list average date-comparison

我有4个列表,包括UNIX中的时间数据和相应的速度。一套比另一套大。我想在较小列表的每个匹配时间戳上找到较大列表的找到值之前和之后的几个值的平均速度。

t1 = [2, 5, 7]

t2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

v1 = [0.5, 1, 0.7]

v2 = [0.1, 0.5, 1, 1.3, 1.4, 1.8, 0.9, 2, 1.5, 1.2]

因此,如果t1和t2匹配,我想在此时间之前和之后得到x值的平均速度。

假设x = 1 在这种情况下,它应该给我平均值(0.1,0.5,1)(1.3,1.4,1.8)和(1.8,0.9,2)

1 个答案:

答案 0 :(得分:0)

尝试

import numpy as np

for num in t1: #for each value in t1
    try:
        match_index=t2.index(num) #check if match exists
    except:
        match_index=-1 #otherwise set it to -1

    if(match_index!=-1): #if match was found
        my_list=[]       #make an empty list 
        if(match_index==0): #if index was 0, then nearby 3 elements can't be found, only 2 can
            my_list=v2[:match_index+2]
        elif(match_index==len(v2)-1): #similarly if index was for last element
            my_list=v2[match_index-1:]
        else:
            my_list=v2[match_index-1:match_index+2] #normal case slice the required values
        print("average of :",my_list," is ",np.average(my_list))

#average of : [0.1, 0.5, 1]  is  0.5333333333333333
#average of : [1.3, 1.4, 1.8]  is  1.5
#average of : [1.8, 0.9, 2]  is  1.5666666666666667