简体   繁体   中英

python iterating through lists

Consider the lists below

filters= [u,    i,  g,    r,    z]
result = [None, 34, None, None, 45]

the items in the result are computed for each filter in filters . It happens that filters, u, g, z did not return any results. So i would to re-compute the values of result[0], result[2], result[4], using the filters that returned values.

My problem is iterating through both lists and using the closet filter to compute a value missing in result. eg result[0] should be computed using 'i' ( i is closest to u ) result[2] we also use 'i' not 'z' and result[3] we use 'z' . How to generalize this?? (filters are fixed, but items in values keep changing.) What i would like to get is a tuple with two filters, (filter_missing_a_value_in_results, filter_to_used_to_computer_the_missing_value)

Not particularly efficient solution:

def filters_by_distance(i):
    '''Generate filters by distance from i'''
    sorted_indices = sorted(range(len(filters)), key=lambda j: abs(j-i))
    return (filters[j] for j in sorted_indices)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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