多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 1. collections模块 ### 1.1 tuple 1. 不可变性和iterable ~~~ tuna = ('dailin',28,'it') tuna[1]=18 Traceback (most recent call last): File "E:/PythonTest/collectiontest/tuple_test.py", line 5, in <module> tuna[1]=18 TypeError: 'tuple' object does not support item assignment ~~~ 2. 拆包 ~~~ tuna = ('dailin',28,'it') # 拆包 name,age,work = tuna print(name,age,work) ~~~ 3. 不可变是绝对的 ~~~ tuna1 = ('dailin',28,['hello','hello']) tuna1[2][1]=18 print(tuna1) ~~~ ~~~ ('dailin', 28, ['hello', 18]) ~~~ ### 1.2 namedtuple 顾名思义就是将tuple命名,类似于C语言中的struct。通常访问tuple利用下标的方式访问例如tuple[1],然而通过给tuple命名,就可以通过name.shuxing的形式访问。 ~~~ __author__ = 'dailin' from collections import namedtuple # 第一个是 name,第二个参数是所有 item 名字的列表。 man = namedtuple("people",["name","age","work"]) person = man("tuna",28,"it") print(type(man)) print(person) print(person.name,person.age,person.work) print("===============") women = ("huanhuan",27,"wife") person1 = man(*women) # 将元组展开,**将字典展开 print(person1.name,person1.age,person1.work) ~~~ 输出: ~~~ <class 'type'> people(name='tuna', age=28, work='it') tuna 28 it =============== huanhuan 27 wife ~~~ ### 1.3 ** 展开字典(一个个键值对),*展开元组 ~~~ __author__ = 'dailin' h = {'name':'tuna','age':28} class People(object): def __init__(self,name,age): print("name:{0},age:{1}".format(name,age)) People(**h) People(h) # 报错 ~~~ ~~~ __author__ = 'dailin' h = {'name':'tuna','age':28} class People(object): def __init__(self,name,age): print("name:{0},age:{1}".format(name,age)) People(**h) People(h) ~~~