x [x<是什么? 2] = 0在Python中意味着什么? [英] What does x[x < 2] = 0 mean in Python?
问题描述
我碰到了一些代码,类似一行
I came across some code with a line similar to
x[x<2]=0
不断尝试各种变化,我仍然坚持使用此语法.
Playing around with variations, I am still stuck on what this syntax does.
示例:
>>> x = [1,2,3,4,5]
>>> x[x<2]
1
>>> x[x<3]
1
>>> x[x>2]
2
>>> x[x<2]=0
>>> x
[0, 2, 3, 4, 5]
推荐答案
这仅在 NumPy 数组.列表的行为是无用的,并且特定于Python 2(不是Python 3).您可能需要仔细检查原始对象是否确实是NumPy数组(请参见下文)而不是列表.
This only makes sense with NumPy arrays. The behavior with lists is useless, and specific to Python 2 (not Python 3). You may want to double-check if the original object was indeed a NumPy array (see further below) and not a list.
但是在您的代码中,x是一个简单的列表.
But in your code here, x is a simple list.
因为
x < 2
是错误的 即0,因此
x[x<2]
是x[0]
x[0]
被更改.
相反,x[x>2]
是x[True]
或x[1]
因此,x[1]
被更改了.
为什么会这样?
比较规则是:
-
当您对两个字符串或两个数字类型进行排序时,将以预期的方式进行排序(字符串的字典顺序,整数的数字顺序).
When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers).
订购数字和非数字类型时,数字类型优先.
When you order a numeric and a non-numeric type, the numeric type comes first.
当您订购两个都不兼容的不兼容类型时,它们都不是数字,而是按其类型名的字母顺序排序:
When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames:
所以,我们有以下顺序
数字<清单<字符串<元组
numeric < list < string < tuple
请参见 Python如何比较字符串和整数的答案? .
如果x是NumPy数组,则由于布尔数组索引,该语法更有意义.在这种情况下,x < 2
根本不是布尔值.它是一个布尔数组,表示x
的每个元素是否小于2.x[x < 2] = 0
然后选择x
的元素小于2,并将这些单元格设置为0.请参见
If x is a NumPy array, then the syntax makes more sense because of boolean array indexing. In that case, x < 2
isn't a boolean at all; it's an array of booleans representing whether each element of x
was less than 2. x[x < 2] = 0
then selects the elements of x
that were less than 2 and sets those cells to 0. See Indexing.
>>> x = np.array([1., -1., -2., 3])
>>> x < 0
array([False, True, True, False], dtype=bool)
>>> x[x < 0] += 20 # All elements < 0 get increased by 20
>>> x
array([ 1., 19., 18., 3.]) # Only elements < 0 are affected
这篇关于x [x<是什么? 2] = 0在Python中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!