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

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

问题描述

这出现在 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...不是隐藏功能,它只是一个常量.例如,它与JavaScript ES6完全不同,后者是语言语法的一部分.没有内置的类或Python语言构造函数使用它.

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使用它,如文档所述. 此处.

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

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

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

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

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