【python基础】省略号...的用法

转载自: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)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值