Python 'in' operator returns an invalid value

I ran into a weird problem with the 'in' operator for python, which plays from the ipython shell below:

    In [119]: Teff = 10000

    In [120]: loggs = numpy.arange(4.5, 4*numpy.log10(Teff) - 15.02, -0.1)

    In [121]: 4.0 in loggs
    Out[121]: False

    In [122]: loggs
    Out[122]: 
    array([ 4.5,  4.4,  4.3,  4.2,  4.1,  4. ,  3.9,  3.8,  3.7,  3.6,  3.5,
    3.4,  3.3,  3.2,  3.1,  3. ,  2.9,  2.8,  2.7,  2.6,  2.5,  2.4,
    2.3,  2.2,  2.1,  2. ,  1.9,  1.8,  1.7,  1.6,  1.5,  1.4,  1.3,
    1.2,  1.1,  1. ])

As you can see, 4.0 is in the array, but the 'in' operator returns False. I tried the same thing with "4" (integer) and "4", both with the same result. Same thing with other values ​​in this array (e.g. 3.9). Any ideas? I am running python 2.7.1, with numpy version 1.7.0.

I saw a previous post that is close, but there has never been a good answer to what happened with 'in'.

+3
source share
3 answers

, 4.0 . , 4.0, (- ) , , "4.0" .

(loggs[5]), , , , 4.0 ( 4.0000000000000018).

.

+7

4.0 , , :

loggs.tolist()

, , 4.0, - :

new_loggs = [round(i,2) for i in loggs.tolist()]
4.0 in new_loggs

: True

0

Loop the matrix with conditional expressions or the range that you want to get from the matrix.

import numpy as np
Teff = 10000
loggs = np.arange(4.5, 4*np.log10(Teff) - 15.02, -0.1)
print loggs
for i in loggs:
    if i > 3.9:
        print i

Conclusion: 4.5 4.4 4.3 4.2 4.1 4.0 3.9

-1
source

All Articles