collections.namedtuple是一个工厂函数,它可以用来构建一个带字段名的元组和一个有名字的类——这个带名字的类对调试程序有很大帮助。
以往存在一定量数据习惯以列表或json的方式保存,例如:
列表:
1 nodes = [ 2 [‘192.168.1.1‘, 22, ‘guest‘], 3 [‘192.168.1.2‘, 22, ‘guest‘], 4 ] 5 for i in nodes: 6 print(i[1])
列表的坏处是以数字作脚注,数据对应关系不直观
json:
1 nodes = [ 2 {‘ip‘: ‘192.168.1.1‘, ‘port‘: 22, ‘user‘: ‘guest‘}, 3 {‘ip‘: ‘192.168.1.2‘, ‘port‘: 22, ‘user‘: ‘guest‘}, 4 ] 5 for i in nodes: 6 print(i[‘user‘])
效率不算特别好,随着数量增大冗余字段名越多,相对比较占用内存
namedtuple:
1 myOpt = namedtuple(‘node‘, ‘ip port user‘) 2 nodes = [ 3 myOpt(‘192.168.1.1‘, 22, ‘guest‘), 4 myOpt(‘192.168.1.2‘, 22, ‘guest‘) 5 ] 6 for i in nodes: 7 print(i.user)
占用内存相对较小,而且字段名直观
原文地址:https://www.cnblogs.com/hell-west-road/p/11331986.html
时间: 2024-11-06 09:51:16