全国旗舰校区

不同学习城市 同样授课品质

北京

深圳

上海

广州

郑州

大连

武汉

成都

西安

杭州

青岛

重庆

长沙

哈尔滨

南京

太原

沈阳

合肥

贵阳

济南

下一个校区
就在你家门口
+
当前位置:首页  >  技术干货  >  详情

用Python的特性来切片无限生成器

来源:千锋教育
发布人:xqq
2023-11-06

推荐

在线提问>>

注解推迟评估

Python3.7中,只要激活了正确的__future__标志,注解在运行时就不会被评估:

from__future__importannotations

defanother_brick(wall:List[Brick],brick:Brick)->Education:

pass

another_brick.__annotations__

{'wall':'List[Brick]','brick':'Brick','return':'Education'}

它使递归类型(指向自己的类)和其他有趣的事情成为了可能。然而,这意味着如果你想做自己的类型分析,你需要明确地使用ast。

importast

raw_type=another_brick.__annotations__['wall']

[parsed_type]=ast.parse(raw_type).body

subscript=parsed_type.value

f"{subscript.value.id}[{subscript.slice.id}]"

'List[Brick]'

itertools.islice支持index

Python中的序列切片长期以来一直接受各种类int对象(具有__index__()的对象)作为有效的切片部分。然而,直到Python3.7,itertools.islice,即核心Python中对无限生成器进行切片的唯一方法,才获得了这种支持。

例如,现在可以用numpy.short大小的整数来切片无限生成器:

importnumpy

short_1=numpy.short(1)

short_3=numpy.short(3)

short_1,type(short_1)

(1,numpy.int16)

importitertools

list(itertools.islice(itertools.count(),short_1,short_3))

[1,2]

functools.singledispatch()注解注册

如果你认为singledispatch已经很酷了,你错了。现在可以根据注解来注册了:

importattr

importmath

fromfunctoolsimportsingledispatch

@attr.s(auto_attribs=True,frozen=True)

classCircle:

radius:float

@attr.s(auto_attribs=True,frozen=True)

classSquare:

side:float

@singledispatch

defget_area(shape):

raiseNotImplementedError("cannotcalculateareaforunknownshape",

shape)

@get_area.register

def_get_area_square(shape:Square):

returnshape.side**2

@get_area.register

def_get_area_circle(shape:Circle):

returnmath.pi*(shape.radius**2)

get_area(Circle(1)),get_area(Square(1))

(3.141592653589793,1)

以上内容为大家介绍了用Python的特性来切片无限生成器,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关文章

python字符串需要注意的语法问题

python如何配置Logging处理器

pythonos模块有几种用法?

python如何定制日志输出格式

python析构器是什么意思?

开班信息 更多>>

课程名称
全部学科
咨询

HTML5大前端

Java分布式开发

Python数据分析

Linux运维+云计算

全栈软件测试

大数据+数据智能

智能物联网+嵌入式

网络安全

全链路UI/UE设计

Unity游戏开发

新媒体短视频直播电商

影视剪辑包装

游戏原画

    在线咨询 免费试学 教程领取