使用布尔索引从Python列表中切片元素 [英] Slicing elements from a Python list using Boolean indexing

查看:511
本文介绍了使用布尔索引从Python列表中切片元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了这种在Python中切片列表的方法.我以前从未看过这个,所以我想清楚地理解这一点.

I recently came across this way of slicing a list in Python. I've never seen this one before, so I would like to understand this clearly.

我有一个列表["Peter", "James", "Mark"],如果我使用布尔值False对其进行切片,则返回Peter,如果我使用True进行切片,则返回James,如下所示

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
  • ["Peter", "James", "Mark"][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:

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

通过__index__上返回的值. >下标,允许将任意对象与切片一起使用:

The value returned by on obj's __index__ is used when accessing with subscripting, allowing arbitrary objects to be used with slices:

x[obj]

这在某种程度上独立于boolint的子类的事实!您可以在任何对象上达到相同的目的.

This is somewhat independent of the fact that bool is a subclass of int! You may achieve the same with any object.

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

是否为int子类解析了__index__取决于实现细节.

Whether __index__ is resolved for int subclasses depends on implementation detail.

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根据 Python数据模型正确运行.看起来CPython正在采取捷径/性能优化.

PyPy behaves correctly according to the Python datamodel. Looks like CPython is taking a shortcut / performance optimization.

这篇关于使用布尔索引从Python列表中切片元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆