• python中namedtuple函数用法详解


    源码解释:

    1. def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
    2. """Returns a new subclass of tuple with named fields.
    3. >>> Point = namedtuple('Point', ['x', 'y'])
    4. >>> Point.__doc__ # docstring for the new class
    5. 'Point(x, y)'
    6. >>> p = Point(11, y=22) # instantiate with positional args or keywords
    7. >>> p[0] + p[1] # indexable like a plain tuple
    8. 33
    9. >>> x, y = p # unpack like a regular tuple
    10. >>> x, y
    11. (11, 22)
    12. >>> p.x + p.y # fields also accessible by name
    13. 33
    14. >>> d = p._asdict() # convert to a dictionary
    15. >>> d['x']
    16. 11
    17. >>> Point(**d) # convert from a dictionary
    18. Point(x=11, y=22)
    19. >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
    20. Point(x=100, y=22)
    21. """

    语法结构:

    namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
    • typename: 代表新建的一个元组的名字。
    • field_names: 是元组的内容,是一个类似list的[‘x’,‘y’]

    命名元组,使得元组可像列表一样使用key访问(同时可以使用索引访问)。

    collections.namedtuple 是一个工厂函数,它可以用来构建一个带字段名的元组和一个有名字的类.

    创建一个具名元组需要两个参数,一个是类名,另一个是类的各个字段的名字。

    存放在对应字段里的数据要以一串参数的形式传入到构造函数中(注意,元组的构造函数却只接受单一的可迭代对象)。

    命名元组还有一些自己专有的属性。最有用的:类属性_fields、类方法 _make(iterable)和实例方法_asdict()。

    示例代码1:

    1. from collections import namedtuple
    2. # 定义一个命名元祖city,City类,有name/country/population/coordinates四个字段
    3. city = namedtuple('City', 'name country population coordinates')
    4. tokyo = city('Tokyo', 'JP', 36.933, (35.689, 139.69))
    5. print(tokyo)
    6. # _fields 类属性,返回一个包含这个类所有字段名称的元组
    7. print(city._fields)
    8. # 定义一个命名元祖latLong,LatLong类,有lat/long两个字段
    9. latLong = namedtuple('LatLong', 'lat long')
    10. delhi_data = ('Delhi NCR', 'IN', 21.935, latLong(28.618, 77.208))
    11. # 用 _make() 通过接受一个可迭代对象来生成这个类的一个实例,作用跟City(*delhi_data)相同
    12. delhi = city._make(delhi_data)
    13. # _asdict() 把具名元组以 collections.OrderedDict 的形式返回,可以利用它来把元组里的信息友好地呈现出来。
    14. print(delhi._asdict())

    运行结果:

    示例代码2:

    1. from collections import namedtuple
    2. Person = namedtuple('Person', ['age', 'height', 'name'])
    3. data2 = [Person(10, 1.4, 'xiaoming'), Person(12, 1.5, 'xiaohong')]
    4. print(data2)
    5. res = data2[0].age
    6. print(res)
    7. res2 = data2[1].name
    8. print(res2)

    运行结果:

    示例代码3:

    1. from collections import namedtuple
    2. card = namedtuple('Card', ['rank', 'suit']) # 定义一个命名元祖card,Card类,有rank和suit两个字段
    3. class FrenchDeck(object):
    4. ranks = [str(n) for n in range(2, 5)] + list('XYZ')
    5. suits = 'AA BB CC DD'.split() # 生成一个列表,用空格将字符串分隔成列表
    6. def __init__(self):
    7. # 生成一个命名元组组成的列表,将suits、ranks两个列表的元素分别作为命名元组rank、suit的值。
    8. self._cards = [card(rank, suit) for suit in self.suits for rank in self.ranks]
    9. print(self._cards)
    10. # 获取列表的长度
    11. def __len__(self):
    12. return len(self._cards)
    13. # 根据索引取值
    14. def __getitem__(self, item):
    15. return self._cards[item]
    16. f = FrenchDeck()
    17. print(f.__len__())
    18. print(f.__getitem__(3))

    运行结果:

    示例代码4:

    1. from collections import namedtuple
    2. person = namedtuple('Person', ['first_name', 'last_name'])
    3. p1 = person('san', 'zhang')
    4. print(p1)
    5. print('first item is:', (p1.first_name, p1[0]))
    6. print('second item is', (p1.last_name, p1[1]))

    运行结果:

    示例代码5:   【_make 从存在的序列或迭代创建实例】

    1. from collections import namedtuple
    2. course = namedtuple('Course', ['course_name', 'classroom', 'teacher', 'course_data'])
    3. math = course('math', 'ERB001', 'Xiaoming', '09-Feb')
    4. print(math)
    5. print(math.course_name, math.course_data)
    6. course_list = [
    7. ('computer_science', 'CS001', 'Jack_ma', 'Monday'),
    8. ('EE', 'EE001', 'Dr.han', 'Friday'),
    9. ('Pyhsics', 'EE001', 'Prof.Chen', 'None')
    10. ]
    11. for k in course_list:
    12. course_i = course._make(k)
    13. print(course_i)

    运行结果:

    示例代码6:    【_asdict 返回一个新的ordereddict,将字段名称映射到对应的值】

    1. from collections import namedtuple
    2. person = namedtuple('Person', ['first_name', 'last_name'])
    3. zhang_san = ('Zhang', 'San')
    4. p = person._make(zhang_san)
    5. print(p)
    6. # 返回的类型不是dict,而是orderedDict
    7. print(p._asdict())

    运行结果:

    示例代码7:   【_replace 返回一个新的实例,并将指定域替换为新的值】

    1. from collections import namedtuple
    2. person = namedtuple('Person', ['first_name', 'last_name'])
    3. zhang_san = ('Zhang', 'San')
    4. p = person._make(zhang_san)
    5. print(p)
    6. p_replace = p._replace(first_name='Wang')
    7. print(p_replace)
    8. print(p)
    9. p_replace2 = p_replace._replace(first_name='Dong')
    10. print(p_replace2)

    运行结果:

    示例代码8:   【_fields 返回字段名】

    1. from collections import namedtuple
    2. person = namedtuple('Person', ['first_name', 'last_name'])
    3. zhang_san = ('Zhang', 'San')
    4. p = person._make(zhang_san)
    5. print(p)
    6. print(p._fields)

    运行结果:

    示例代码9:   【利用fields可以将两个namedtuple组合在一起】

    1. from collections import namedtuple
    2. person = namedtuple('Person', ['first_name', 'last_name'])
    3. print(person._fields)
    4. degree = namedtuple('Degree', 'major degree_class')
    5. print(degree._fields)
    6. person_with_degree = namedtuple('person_with_degree', person._fields + degree._fields)
    7. print(person_with_degree._fields)
    8. zhang_san = person_with_degree('san', 'zhang', 'cs', 'master')
    9. print(zhang_san)

    运行结果:

    示例代码10:   【field_defaults】

    1. from collections import namedtuple
    2. person = namedtuple('Person', ['first_name', 'last_name'], defaults=['san'])
    3. print(person._fields)
    4. print(person._field_defaults)
    5. print(person('zhang'))
    6. print(person('Li', 'si'))

    运行结果:

    示例代码11:   【namedtuple是一个类,所以可以通过子类更改功能】

    1. from collections import namedtuple
    2. Point = namedtuple('Point', ['x', 'y'])
    3. p = Point(4, 5)
    4. print(p)
    5. class Point(namedtuple('Point', ['x', 'y'])):
    6. __slots__ = ()
    7. @property
    8. def hypot(self):
    9. return self.x + self.y
    10. def hypot2(self):
    11. return self.x + self.y
    12. def __str__(self):
    13. return 'result is %.3f' % (self.x + self.y)
    14. aa = Point(4, 5)
    15. print(aa)
    16. print(aa.hypot)
    17. print(aa.hypot2)

    运行结果:

    示例代码12:   【注意观察两种写法的不同】

    1. from collections import namedtuple
    2. Point = namedtuple("Point", ["x", "y"])
    3. p = Point(11, 22)
    4. print(p)
    5. print(p.x, p.y)
    6. # namedtuple本质上等于下面写法
    7. class Point2(object):
    8. def __init__(self, x, y):
    9. self.x = x
    10. self.y = y
    11. o = Point2(33, 44)
    12. print(o)
    13. print(o.x, o.y)

    运行结果:

  • 相关阅读:
    JS Map与weakMap
    rust编程初探-猜数游戏(chapter 2)
    BI数据分析
    保护敏感数据的艺术:数据安全指南
    STM32F4x_中断配置
    Spring注解详解:@ComponentScan自动扫描组件使用
    汽车售后接待vr虚拟仿真实操演练作为岗位培训的重要工具和手段
    2021 XV6 4:traps
    科学计算库 —— Matplotlib
    UG\NX二次开发 连接曲线、连结曲线 UF_CURVE_auto_join_curves
  • 原文地址:https://blog.csdn.net/weixin_44799217/article/details/126594612