Several basic usages in python: namedtuple, OrderedDict, append, insert, extend

python中:namedtuple,OrderedDict,append,insert,extend


Although I don't like to re-invent the wheel, I personally prefer to post something that is not available on the Internet, but if you write some basic things yourself, you should leave an impression on yourself. The following is an introduction to several commonly used python modules in the process of looking at the code:
(ps: The python version tested below is 3.7)

One, namedtuple

This method comes from Python's built-in collections: container data type , the official website introduces:

This module implements a target-specific container to provide alternatives to the Python standard built-in containers dict, list, set, and tuple.

We know that general tuple elements cannot be changed, and the elements can only be accessed through indexing, but named tuples are much more convenient, readable and operability.
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

  • Return a new tuple subclass named typename. This new subclass is used to create objects of class tuples, which can obtain attribute values ​​through domain names (field_names), as well as through indexing and iteration.
  • The domain name (field_names) is a sequence of strings like ['x','y']. In addition, field_names can be a pure string, separated by blanks or commas, such as'x y'or'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))

二、OrderedDict

This is also an alternative to dict in the collections: container data type : collections.OrderedDict([items])

Ordered dictionaries are just like regular dictionaries, but have some additional functions related to sorting operations. Note: The built-in dict class in Python 3.6/3.7 also has the ability to remember the insertion order (python3.5 does not yet). Originally, the biggest difference is faded [I only knew this when I was writing this]

>>> 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')])

Three, append

This is a method of the commonly used list: array.append(x)

Add a new item with value x to the end of the array

>>> 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)]

Four, insert

Mainly this is not commonly used: array.insert(i, x)

Insert the value x as a new item before the i position of the array. Negative values ​​will be considered relative to the end of the array

>>> 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]

Five, extend

This one is also not commonly used: array.extend(iterable) :

Add items from iterable to the end of the array. If iterable is another array, it must have exactly the same type code; otherwise, TypeError will be raised. If iterable is not an array, it must be an iterable object and its elements must be of the appropriate type that can be added to the array.

>>> 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']

More information about lists can be found here:
array — Efficient arrays of numeric values
[I don’t know why it’s called array, not list]

Guess you like

Origin blog.csdn.net/laizi_laizi/article/details/105437368