x[x<2]=0在Python中是什么意思?

2024-04-19 19:52:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现一些代码的行类似于

x[x<2]=0

我在玩变奏曲时,仍然纠结于这种语法的作用。

示例:

>>> 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]

Tags: 代码示例语法变奏曲
3条回答

问题中的原始代码仅在Python2中有效。如果x是Python 2中的list,那么比较x < yFalse,如果y是一个int元素。这是因为将列表与整数进行比较是没有意义的。然而,在Python 2中,如果操作数不可比较,则比较基于CPython中的alphabetical ordering of the names of the types;此外,在混合类型比较中,所有数字都排在第一位。这甚至没有在CPython 2的文档中阐明,不同的python2实现可能会给出不同的结果。也就是说,[1, 2, 3, 4, 5] < 2的计算结果是False,因为2是一个数字,因此比CPython中的list小。这种混合比较最终被deemed to be too obscure a feature,并在Python 3.0中删除。


现在,<的结果是abool;和^{} is a subclass of ^{}

>>> isinstance(False, int)
True
>>> isinstance(True, int)
True
>>> False == 0
True
>>> True == 1
True
>>> False + 5
5
>>> True + 5
6

所以基本上,根据比较结果是真是假,取元素0或1。


如果您在Python 3中尝试上面的代码,您将得到TypeError: unorderable types: list() < int(),原因是a change in Python 3.0

Ordering Comparisons

Python 3.0 has simplified the rules for ordering comparisons:

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.


有许多数据类型可以重载比较运算符来执行不同的操作(pandas和numpy数组中的数据帧)。如果您正在使用的代码做了其他事情,那是因为x不是list,而是一个其他类的实例,它的运算符<被重写以返回一个不是bool的值;然后这个值由x[](又名__getitem__/__setitem__)特别处理

这只对NumPy数组有意义。使用列表的行为是无用的,并且特定于Python2(而不是Python3)。您可能需要再次检查原始对象是否确实是一个NumPy数组(请参见下面的进一步内容),而不是一个列表。

但在这里的代码中,x是一个简单的列表。

自从

x < 2

是假的 i、 因此,e 0

x[x<2]x[0]

x[0]被更改。

相反,x[x>2]x[True]x[1]

所以,x[1]被改变了。

为什么会这样?

比较的规则是:

  1. 当您订购两个字符串或两个数字类型时,将按预期的方式进行排序(字符串的字典式排序,整数的数字排序)。

  2. 当您订购数值型和非数值型时,数值型优先。

  3. 当您订购两种不兼容的类型时,如果这两种类型都不是数字,则按其类型名的字母顺序排序:

所以,我们有以下订单

数字<;列表<;字符串<;元组

请参阅How does Python compare string and int?的公认答案。

如果x是NumPy数组,则语法更合理,因为布尔数组索引。在这种情况下,x < 2根本不是布尔值;它是一个布尔值数组,表示x的每个元素是否小于2。x[x < 2] = 0然后选择x中小于2的元素,并将这些单元格设置为0。见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 = [1,2,3,4,5]
>>> x<2
False
>>> x[False]
1
>>> x[True]
2

bool被简单地转换成一个整数。索引为0或1。

相关问题 更多 >