简体   繁体   中英

Setting to zero of elements of a numpy array different from a value (python3) : a[a <> 5] = 0

In python 2, the following code works:

a = np.array([[1,5],[2,3]])
print a
print()
a[a<2] = 0
print a
a[a <> 5] = 0
print a

But in python3, it triggers a syntax error:

a[a <> 5] = 0

File "<ipython-input-14-165e29d9f8e4>", line 1
    a[a <> 5] = 0
         ^
SyntaxError: invalid syntax

The correct syntax for "not equal to" is now a[a != 5] = 0

(Yet another instance of a backward compatibility break in Python 3).

In Python 3, <> was replaced by != . It is similar to how print was changed from a statement to a function. See Comparisons in the Docs:

!= can also be written <> , but this is an obsolete usage kept for backwards compatibility only. New code should always use != .

Ps: You can be quite sneaky and do:

from __future__ import barry_as_FLUFL

which allows <> and makes != a SyntaxError, but really don't, just use != .

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