python中幾個基本用法:namedtuple,OrderedDict,append,insert,extend
阿新 • • 發佈:2021-01-08
https://blog.csdn.net/laizi_laizi/article/details/105437368
python中幾個基本用法:namedtuple,OrderedDict,append,insert,extend
laizi_laizi2020-04-11 00:51:08229收藏1 分類專欄:python 版權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)