简体   繁体   English

使用布尔索引从Python列表中切割元素

[英]Slicing elements from a Python list using Boolean indexing

I recently came across this way of slicing a list in Python. 我最近遇到过用Python切片列表的方式。 I've never seen this one before, so I would like to understand this clearly. 我以前从未见过这个,所以我想清楚地理解这一点。

I have a list ["Peter", "James", "Mark"] and if I slice it using the boolean value False it returns Peter and if I slice using True it returns James , as given below 我有一个列表["Peter", "James", "Mark"]如果我使用布尔值False对其进行切片,则返回Peter ,如果我使用True切片,则返回James ,如下所示

  • ["Peter", "James", "Mark"][False] => Peter
  • ["Peter", "James", "Mark"][True] => James

I would like to know what happens here and what is this method called as? 我想知道这里发生了什么,这个方法叫做什么?

The datamodel hook here is the __index__ magic method: 这里的__index__钩子是__index__魔术方法:

>>> True.__index__()
1
>>> False.__index__()
0

The value returned by on obj's __index__ is used when accessing with subscripting , allowing arbitrary objects to be used with slices: 当使用下标访问时,使用obj的__index__返回的值,允许任意对象与切片一起使用:

x[obj]

This is somewhat independent of the fact that bool is a subclass of int ! 这有点独立于boolint的子类这一事实! You may achieve the same with any object. 您可以使用任何对象实现相同的目标。

>>> class A:
...     def __index__(self):
...         return 1
...     
>>> 'ab'[A()]
'b'

Whether __index__ is resolved for int subclasses depends on implementation detail. 是否为int子类解析__index__取决于实现细节。

CPython 3.7.1: CPython 3.7.1:

>>> class MyInt(int):
...     def __index__(self):
...         return 1
... 
>>> '01'[MyInt(0)]
'0'

PyPy 5.0.1: PyPy 5.0.1:

>>>> class MyInt(int):
....     def __index__(self):
....         return 1
....         
>>>> '01'[MyInt(0)]
'1'

PyPy behaves correctly according to the Python datamodel . PyPy根据Python数据模型正确运行。 Looks like CPython is taking a shortcut / performance optimization. 看起来CPython正在进行快捷/性能优化。

In Python, bool class is derived from of int Hence True=1 and False=0 在Python中, bool类派生自int因此True=1False=0

print (True + True) will give an output 2 print (True + True)将给出输出2

So on a list ['peter', 'john', 'abhi'][True] returns 2nd element of the list ie john 所以在列表中['peter', 'john', 'abhi'][True]返回列表中的第二个元素,即john

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM