where or filter on list

skip at pobox.com skip at pobox.com
Wed Aug 30 08:18:02 EDT 2006


    >>>> foo = [-5,-1,2,3] # nearest value to zero ?
    >>>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for x in foo])]
    charles> [-1]

    charles> Something simpler ?

Well, you can just use the abs() builtin instead of math.fabs.  Also, just
compute the min/abs once:

    minval = min([int(math.fabs(x)) for x in foo])
    [value for value in foo if fabs(value) == minval]

Another way might be to sort by absolute value:

    intermed = [(abs(v), v) for v in foo]
    intermed.sort()
    intermed[0][1]

That only gives you one of possibly many values closest to zero.

    charles> How to extend this function to any given value ?

Just subtract that value from all values in the list:

    intermed = [(abs(v-x), v) for v in foo]
    intermed.sort()
    intermed[0][1]

Skip



More information about the Python-list mailing list