1. 程式人生 > 實用技巧 >python中幾個基本用法:namedtuple,OrderedDict,append,insert,extend

python中幾個基本用法:namedtuple,OrderedDict,append,insert,extend

https://blog.csdn.net/laizi_laizi/article/details/105437368

python中幾個基本用法:namedtuple,OrderedDict,append,insert,extend

2020-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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

二、OrderedDict

這也是collections: 容器資料型別裡面對於dict的一種替代選擇:collections.OrderedDict([items])

有序詞典就像常規詞典一樣,但有一些與排序操作相關的額外功能。注意:在Python 3.6/3.7中內建的 dict 類也有記住插入順序的能力(python3.5還沒有),本來這一個最大的區別也就淡化了【我也是寫這篇的時候才知道這個】

>>> from collections import OrderedDict
>>> d1={}
>>> d1['a']='A'
>>> d1['b']='B'
>>> d1['c']='C'
>>>> for k,v in d1.items():      # 在python3.7裡面也是記住順序了
...     print(k,v)               # 在3.5會打亂順序輸出的
...
a A
b B
c C
>>> d2={}
>>> d2['c']='C'
>>> d2['b']='B'
>>> d2['a']='A'
>>>> d1
{'a': 'A', 'b': 'B', 'c': 'C'}
>>>> d2
{'c': 'C', 'b': 'B', 'a': 'A'}
>>> d1 == d2                     # 這裡注意,普通字典還是相等的,區別這裡來了
True
>>> d3 = OrderedDict()
>>> d4 = OrderedDict()
>>> d3['a']='A'
>>> d3['b']='B'
>>> d3['c']='C'
>>> d4['c']='C'
>>> d4['b']='B'
>>> d4['a']='A'
>>> d3
OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')])
>>> d4
OrderedDict([('c', 'C'), ('b', 'B'), ('a', 'A')])
>>> d3 == d4                     # 記住順序好像一樣了,但是這不一樣
False
>>> new_list = [("name", "lsm"), ("sex", "male"), ("face", "handsome")]
>>> new_dict = OrderedDict(new_list)
>>> new_dict
OrderedDict([('name', 'lsm'), ('sex', 'male'), ('face', 'handsome')])
>>> ano_dict = OrderedDict.fromkeys(new_list)
>>> ano_dict
OrderedDict([(('name', 'lsm'), None), (('sex', 'male'), None), (('face', 'handsome'), None)])
>>> k,v = new_dict.popitem()
>>> k,v
('face', 'handsome')
>>> new_dict.move_to_end('name')
>>> new_dict
OrderedDict([('sex', 'male'), ('name', 'lsm')])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

三、append

這個是大家常用的列表的一個方法:array.append(x)

新增一個值為 x 的新項到陣列末尾

>>> a = [1, 2, 3]
>>> a.append(4)
>>> a.append(5,6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 given)
>>> a.append((5,6))
>>> a
[1, 2, 3, 4, (5, 6)]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

四、insert

主要這個不太常用到:array.insert(i, x)

將值 x 作為新項插入陣列的 i 位置之前。 負值將被視為相對於陣列末尾的位置

>>> a = [1, 2, 3]
>>> a.insert(0, 0)
>>> a
[0, 1, 2, 3]
>>> a.insert(1, 0.5)
>>> a
[0, 0.5, 1, 2, 3]
>>> a.insert(-1, 9)
>>> a
[0, 0.5, 1, 2, 9, 3]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

五、extend

這個也不太常用到:array.extend(iterable)

將來自 iterable 的項新增到陣列末尾。 如果 iterable 是另一個數組,它必須具有 完全 相同的型別碼;否則將引發 TypeError。 如果 iterable 不是一個數組,則它必須為可迭代物件並且其元素必須為可新增到陣列的適當型別。

>>> a = [1, 2, 3]
>>> a.extend(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> a.extend((4,5))   # 注意與append的區別
>>> a
[1, 2, 3, 4, 5]
>>> a.extend([6,7])
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> a.extend((8,))
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> a.extend(('lz',))
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 'lz']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

更多關於列表的方法可以在這找到:
array — Efficient arrays of numeric values
【不知道為什麼叫array,不叫list】