namedtuple类位于collections模块,有了namedtuple后通过属性访问数据能够让我们的代码更加的直观更好维护

namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数据,能够迭代,还能够方便的通过属性名来访问数据

from collections import namedtuple
Friend =namedtuple("Friend",['name','age','email'])
f1=Friend('giga',38,'gaga@qq.com')
print(f1)
print(f1.age)
print(f1.email)
f2=Friend(name='jjuu',email='eeee@qw.com',age=15)
print(f2)

name,age,email=f2
print(name,age,email)



out
Friend(name='giga', age=38, email='gaga@qq.com')
38
gaga@qq.com
Friend(name='jjuu', age=15, email='eeee@qw.com')
jjuu 15 eeee@qw.com

 

note:

1.namedtuple的属性名称不能有 空格( ),斜杠(/),反斜杠(\)等之类的特殊字符,没有进行一一验证,如下错误,可以考虑一下heading里面是不是有特殊字符造成的,只有在列名是合法的Python 标识符的时候才生效

python 简单了解namedtuple

 

相关文章:

  • 2021-07-31
  • 2021-06-01
  • 2022-12-23
  • 2021-07-12
  • 2022-12-23
  • 2021-07-10
  • 2022-03-07
  • 2021-07-26
猜你喜欢
  • 2022-01-24
  • 2021-12-07
  • 2021-05-11
  • 2022-01-27
  • 2021-04-12
  • 2022-12-23
  • 2021-08-02
相关资源
相似解决方案