转载自:https://zhuanlan.zhihu.com/p/489862322
省略号(…)在Python有着广泛的应用,尤其是一些底层代码中,经常能看到大量的省略号(…)。如下图所示就是type这个类的底层代码,可以看到非常多的省略号(…)。这些省略号(…)是什么意思?又有哪些用法呢?本文试图分析一二。

1. 省略号是什么?
省略号(…)的底层代码很简单,如下所示。@final装饰器
的意思是该类不允许被继承。
# Actually the type of Ellipsis is <type 'ellipsis'>, but since it's
# not exposed anywhere under that name, we make it private here.
@final
class ellipsis: ...
Ellipsis: ellipsis
而如下的代码的输出结果说明:Ellipsis就是省略号(…),省略号(…)就是Ellipsis。
而Ellipsis是ellipsis类的唯一实例(singleton object),这种唯一实例的模式也称为单例模式
(singleton pattern)[1]。
print(type(...)) # output: <class 'ellipsis'>
print(Ellipsis == ...) # True
print(...) # Ellipsis
2. 省略号三种用法
类型提示
关于Python中的类型提示(type hints)详见【Python】作为动态语言,Python中的“类型声明”有什么用?。省略号(…)在类型提示中经常被使用,如
from typing import Callable, Tuple
Callable[..., int] # 输入参数随意,返回值为int
Tuple[int, ...] # int组成的元组
函数内部,相当于pass
以下两个写法没有太大区别
def foo1(): pass
def foo2(): ...
numpy中的索引
import numpy as np
arr = np.random.random((2,2,2))
print(arr)
print(arr[..., 0, 0])
import numpy as np
a = np.array([[[1, 2, 21], [3, 4, 34]],
[[5, 6, 56], [7, 8, 78]]])
print("a:",a)
print('a.shape:', a.shape)
print("-"*10)
'''
[...,0:2]针对的是最后一个维度的下标为0、1的元素
'''
b = a[..., 0:2]
print('b :', b)
print('shape.b:', b.shape)
print("-"*10)
'''
[...,1:2]针对的是最后一个维度的下标为1的元素
'''
c = a[..., 1:2]
print('c :', c)
print('shape.c:', c.shape)
print("-"*10)
'''
[...,1]是相当于[-1],倒数第1个维度(-2,-1,-0)
'''
d = a[..., 1]
print('d :', d)
print('shape.d:', d.shape)
运行结果如下:
a: [[[ 1 2 21]
[ 3 4 34]]
[[ 5 6 56]
[ 7 8 78]]]
a.shape: (2, 2, 3)
----------
b : [[[1 2]
[3 4]]
[[5 6]
[7 8]]]
shape.b: (2, 2, 2)
----------
c : [[[2]
[4]]
[[6]
[8]]]
shape.c: (2, 2, 1)
----------
d : [[2 4]
[6 8]]
shape.d: (2, 2)