你如何在 Python 中使用省略号切片语法? [英] How do you use the ellipsis slicing syntax in Python?

查看:30
本文介绍了你如何在 Python 中使用省略号切片语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这出现在 Python 的隐藏特性中,但我看不到好的文档或解释该功能如何工作的示例.

解决方案

Ellipsis... 不是隐藏功能,它只是一个常量.它与 JavaScript ES6 完全不同,它是语言语法的一部分.没有内置类或 Python 语言结构使用它.

因此它的语法完全取决于您或其他人是否编写了代码来理解它.

Numpy 使用它,如文档 中所述.一些示例此处.

在你自己的课堂上,你会像这样使用它:

<预><代码>>>>类 TestEllipsis(对象):... def __getitem__(self, item):...如果项目是省略号:...返回返回所有项目"... 别的:... return "return %r items" % item...>>>x = TestEllipsis()>>>打印 x[2]退回 2 件商品>>>打印 x[...]退回所有物品

当然,还有 python 文档,和语言参考.但这些都不是很有帮助.

This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works.

解决方案

Ellipsis, or ... is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.

So the syntax for it depends entirely on you, or someone else, having written code to understand it.

Numpy uses it, as stated in the documentation. Some examples here.

In your own class, you'd use it like this:

>>> class TestEllipsis(object):
...     def __getitem__(self, item):
...         if item is Ellipsis:
...             return "Returning all items"
...         else:
...             return "return %r items" % item
... 
>>> x = TestEllipsis()
>>> print x[2]
return 2 items
>>> print x[...]
Returning all items

Of course, there is the python documentation, and language reference. But those aren't very helpful.

这篇关于你如何在 Python 中使用省略号切片语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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