zoukankan      html  css  js  c++  java
  • python中几个基本用法:namedtuple,OrderedDict,append,insert,extend

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

    python中几个基本用法:namedtuple,OrderedDict,append,insert,extend

    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】

  • 相关阅读:
    Android进程的优先级说明
    Android的有序广播和无序广播(解决安卓8.0版本之后有序广播的接收问题)
    Android开发中常用Dialog(普通弹窗&时间选择器&日历选择器)
    Android的显示意图和隐式意图总结
    Android的启动模式
    怎么评论一段php语言文本单词one-hot编码的健壮性
    python 基础知识,解决模板引擎实现原理流程
    SQL----EXISTS 关键字EXISTS基本意思
    omcat启动Publishing failed with multiple errors
    AngularJs directive详解及示例代码
  • 原文地址:https://www.cnblogs.com/shuimuqingyang/p/14251075.html
Copyright © 2011-2022 走看看