mardi 6 décembre 2016

Iterate over several lists with different conditions in python

Task: A moving object measures some parameters per second, which should be compared with measurements from ten stationary objects that measures every 10 min.

Conditions: The moving object should be in the range of 100 meters from one of the stationary objects, and in time a +-5 min difference between the moving and stationary measurement, to be able to compare the parameters.

Lists: time_m, time_s, lon_m, lat_m, lon_s, lat_s, param1_m, param1_s, param2_m, param2_s, etc. (m for moving and s for stationary (all measurements from the ten stationary objects are in the same list))

Problem: Since the lists have about 10^5 measurements each my solution with two for loops and two if statements takes way too long time. Please, can you help me solve this in a better way?

My solution:

dt_m = [datetime.datetime.strptime(item, '%Y-%m-%dT%H:%M:%S') for item in time_m]
dt_s = [datetime.datetime.strptime(item, '%Y-%m-%dT%H:%M:%S') for item in time_s]
d = datetime.timedelta(minutes=5)
lon_hundred_m = 0.00180 #lon degrees for 100 m at lat 60
lat_hundred_m = 0.00090 #lat degrees for 100 m

for i in range(len(lon_m)):
    for j in range(len(lon_s)):
        if lon_m[i] >= (lon_s[j]-lon_hundred) and lon_m[i] <= (lon_s[j]+lon_hundred) and lat_m[i] >= (lat_s[j]-lon_hundred) and lat_m[i] <= (lat_s[j]+lon_hundred):
            if dt_s[j] >= dt_m[i]-d and dt_s[j] <= dt_m[i]+d:                
                time_m_2.append(time_m[i])
                param1_m_2.append(param1_m[i])
                param2_m_2.append(param2_m[i])
                lon_m_2.append(lon_m[i])
                lat_m_2.append(lat_m[i])
                time_s_2.append(time_s[j])
                param1_s_2.append(param1_s[j])
                param2_s_2.append(param2_s[j])
                lon_s_2.append(lon_s[j])
                lat_s_2.append(lat_s[j])

Thanks!

Aucun commentaire:

Enregistrer un commentaire