https://blog.csdn.net/laizi_laizi/article/details/105437368
python中几个基本用法:namedtuple,OrderedDict,append,insert,extend
虽然我不太喜欢重复造轮子,个人更喜欢发一些网上少的东西,但是有些基础的东西自己写一写,还是给自己留下一个印象吧,本篇就是如此。下面就是在看代码过程中几个python常用模块的介绍:
(ps:下面试验的python版本为3.7)
一、namedtuple
这个方法来自于python内置的collections: 容器数据类型,官网介绍:
这个模块实现了特定目标的容器,以提供Python标准内建容器 dict , list , set , 和 tuple 的替代选择。
我们知道一般的元组(tuple)元素不能改变,也只能通过索引来访问其中的元素,但是命名元组(namedtuple)就方便很多,可读性和操作性强。
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
- 返回一个新的元组子类,名为 typename 。这个新的子类用于创建类元组的对象,可以通过域名(field_names)来获取属性值,同样也可以通过索引和迭代获取值
- 域名(field_names)是一个像 [‘x’, ‘y’] 一样的字符串序列。另外 field_names 可以是一个纯字符串,用空白或逗号分隔开元素名,比如 ‘x y’ 或者 ‘x, y’
>>> from collections import namedtuple
# 其实point = namedtuple('Point', ['x', 'y'])这样写也不会报错
# 但是还是和typename保持一致比较规范吧
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # 以位置参数或者关键字参数实例化
>>> p[0] + p[1] # 可像普通元组一样索引(11, 22)
33
>>> x, y = p
>>> x, y
(11, 22)
>>> p.x + p.y # 属性可以通过“.”加名字访问
33
>>> p.x = 33 # 属性还是不可以直接更改
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
p.x = 33
AttributeError: can't set attribute
>>> p._replace(x=33) # 这样也不行,是返回一个新的实例
Point(x=33, y=22) # 所以不管是tuple还是namedtuple
>>> p.x # 就用来保存一些不可更改的值的东西吧
11
>>> id(p._replace(x=33))
1618244029320
>>> id(p)
1618244029104
>>> p
Point(x=11, y=22)
# 再来看我实际碰到的一个例子吧
# ResNet stage specification
>>>StageSpec = namedtuple(
"StageSpec",
[
"index", # Index of the stage, eg 1, 2, ..,. 5
"block_count", # Number of residual blocks in the stage
"return_features", # True => return the last feature map from this stage
],
)
>>> ResNet50StagesTo5 = tuple(
StageSpec(index=i, block_count=c, return_features=r)
for (i, c, r) in ((1, 3, False), (2, 4, False),
(3, 6, False), (4, 3, True))
)
>>> ResNet50StagesTo5
(StageSpec(index=1, block_count=3, return_features=False),
StageSpec(index=2, block_count=4, return_features=False),
StageSpec(index=3, block_count=6, return_features=False),
StageSpec(index=4, block_count=3, return_features=True