using list operator “in” with floating point values

前端 未结 3 2024
迷失自我
迷失自我 2021-01-14 11:34

I have a list with floats, each number with 3 decimals (eg. 474.259). If I verify the number in the list like this:

if 474.259 in list_sample:
    print \"so         


        
3条回答
  •  生来不讨喜
    2021-01-14 11:40

    You can use numpy.isclose() instead of Python's in.

    import numpy as np
    other_list = np.array([474.251001, 123.456])
    number = other_list[0]
    number = round(number, 3)
    if number == 474.251:
        print "number == 474.251"
    if number in other_list:
        print "number in other_list"
    if any(np.isclose(number, other_list, rtol=1e-7)):
        print 'any(np.isclose(number, other_list, rtol=1e-7))'
    

    Output:

    number == 474.251
    any(np.isclose(number, other_list, rtol=1e-7))
    

提交回复
热议问题