问题中的原始代码仅在Python2中有效。如果x是Python 2中的list,那么比较x < y是False,如果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中删除。
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.
>>> 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
问题中的原始代码仅在Python2中有效。如果
x
是Python 2中的list
,那么比较x < y
是False
,如果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中删除。现在,} is a subclass of ^{} :
<
的结果是abool
;和^{所以基本上,根据比较结果是真是假,取元素0或1。
如果您在Python 3中尝试上面的代码,您将得到
TypeError: unorderable types: list() < int()
,原因是a change in Python 3.0:有许多数据类型可以重载比较运算符来执行不同的操作(pandas和numpy数组中的数据帧)。如果您正在使用的代码做了其他事情,那是因为
x
不是list
,而是一个其他类的实例,它的运算符<
被重写以返回一个不是bool
的值;然后这个值由x[]
(又名__getitem__
/__setitem__
)特别处理这只对NumPy数组有意义。使用列表的行为是无用的,并且特定于Python2(而不是Python3)。您可能需要再次检查原始对象是否确实是一个NumPy数组(请参见下面的进一步内容),而不是一个列表。
但在这里的代码中,x是一个简单的列表。
自从
是假的 i、 因此,e 0
x[x<2]
是x[0]
x[0]
被更改。相反,
x[x>2]
是x[True]
或x[1]
所以,
x[1]
被改变了。为什么会这样?
比较的规则是:
当您订购两个字符串或两个数字类型时,将按预期的方式进行排序(字符串的字典式排序,整数的数字排序)。
当您订购数值型和非数值型时,数值型优先。
当您订购两种不兼容的类型时,如果这两种类型都不是数字,则按其类型名的字母顺序排序:
所以,我们有以下订单
数字<;列表<;字符串<;元组
请参阅How does Python compare string and int?的公认答案。
如果x是NumPy数组,则语法更合理,因为布尔数组索引。在这种情况下,
x < 2
根本不是布尔值;它是一个布尔值数组,表示x
的每个元素是否小于2。x[x < 2] = 0
然后选择x
中小于2的元素,并将这些单元格设置为0。见Indexing。bool被简单地转换成一个整数。索引为0或1。
相关问题 更多 >
编程相关推荐