码迷,mamicode.com
首页 > 编程语言 > 详细

python之collections模块

时间:2019-01-04 17:11:27      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:tar   rom   定义   cti   用户   test   sequence   mapping   class   

前言:

import collections
print([name for name in dir(collections) if not name.startswith("_")])
[‘AsyncIterable‘, ‘AsyncIterator‘, ‘Awaitable‘, ‘ByteString‘, ‘Callable‘, ‘ChainMap‘, ‘Container‘, ‘Coroutine‘, 
‘Counter‘, ‘Generator‘, ‘Hashable‘, ‘ItemsView‘, ‘Iterable‘, ‘Iterator‘, ‘KeysView‘, ‘Mapping‘, ‘MappingView‘, 
‘MutableMapping‘, ‘MutableSequence‘, ‘MutableSet‘, ‘OrderedDict‘, ‘Sequence‘, ‘Set‘, ‘Sized‘, ‘UserDict‘, ‘UserList‘, 
‘UserString‘, ‘ValuesView‘, ‘abc‘, ‘defaultdict‘, ‘deque‘, ‘namedtuple‘]

 

1.from collections import namedtuple

from collections import namedtuple

# 定义一个namedtuple类型User,并包含name,sex和age属性。
User = namedtuple(‘User‘, [‘name‘, ‘sex‘, ‘age‘])

# 创建一个User对象
user = User(name=‘wqb‘, sex=‘male‘, age=24)

# 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法
user = User._make([‘wqb‘, ‘male‘, 24])

print(user)
# User(name=‘wqb‘, sex=‘male‘, age=24)

# 获取用户的属性
print(user.name)      
print(user.sex)    
print(user.age)    

        
# 修改对象属性,注意要使用"_replace"方法
user = user._replace(age=22)
print(user)
# User(name=‘wqb‘, sex=‘male‘, age=22)

# 将User对象转换成字典,注意要使用"_asdict"
print(user._asdict())
# OrderedDict([(‘name‘, ‘wqb‘), (‘sex‘, ‘male‘), (‘age‘, 22)])

适用地方:

学生信息系统:

       (名字,年龄,性别,邮箱地址)为了减少存储开支,每个学生的信息都以一个元组形式存放

       如:

       (‘tom‘, 18,‘male‘,‘tom@qq.com‘ )

       (‘jom‘, 18,‘mal‘,‘jom@qq.com‘ ) .......

       这种方式存放,如何访问呢?

#!/usr/bin/python3
 
student = (‘tom‘, 18, ‘male‘, ‘tom @ qq.com‘ )
print(student[0])
if student[1] > 12:
    ...
if student[2] == ‘male‘:  
    ...

出现问题,程序中存在大量的数字index,可阅读性太差,无法知道每个数字代替的含义=》

如何解决这个问题?

方法1:

#!/usr/bin/python3
 
# 给数字带上含义,和元组中一一对应
name, age, sex, email = 0, 1, 2, 3                        
# 高级:name, age, sex, email = range(4)
student = (‘tom‘, 18, ‘male‘, ‘tom @ qq.com‘ )
print(student[name])
if student[age] > 12:
     print(‘True‘)
if student[sex] == ‘male‘:
    print(‘True‘)

方法2:

  通过 collections库的 nametuple模块

rom collections import namedtuple
 
# 生成一个Student类
Student = namedtuple(‘Student‘, [‘name‘, ‘age‘, ‘sex‘, ‘email‘])
 
s = Student(‘tom‘, 18, ‘male‘, ‘tom@qq.com‘)

print(s.name, s.age, s.sex, s.email)

 

python之collections模块

标签:tar   rom   定义   cti   用户   test   sequence   mapping   class   

原文地址:https://www.cnblogs.com/wqbin/p/10220488.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!