Python学习——字典和集合
来源:互联网 发布:怎么访问apache服务器 编辑:程序博客网 时间:2024/06/06 05:54
本部分学习于:零基础入门学Python
字典
一. 创建和访问
映射类型,键Key和值Value之间存在对应关系。
创建:
1. 使用大括号,对应元素之间使用冒号,见dict1和dict2
2. 通过构造元组的形式输入其映射关系,见dict3
3. 通过键和值的设置,注意不能有 数字=‘ ’ 或 ‘ ’=‘ ’ 的情况,否则视为等式不成立,见dict4
访问:
1. 直接通过键访问值
2. 可以单独改变某个键对应的值
3.可以创建新的键和值,会自动加入到字典中
dict1 = {'aoi':'蓝色','shiroi':'白色','akai':'红色'}print(dict1['aoi']) #蓝色dict2 = {1:'one',2:'two',3:'three'}print(dict2[3]) #threedict3 = dict(((1,'one'),(2,'two'),(3,'three')))print(dict3) #{1:'one',2:'two',3:'three'}print(dict3[2]) #twodict4 = dict(yi ='one',er ='two',san ='three') print(dict4) #{‘yi’:'one','er':'two','san'='three'}print(dict4['yi']) #onedict4['yi'] = 'ichi'dict4['wu'] = 'five'print(dict4) #{'yi':'ichi','wu'='five','san'='three','er'='two'}
二. 内嵌函数
1.fromkeys()
dict.fromkeys[s[,v]]
返回由s构成键,由v构成值的新字典
第二个参数会自动赋给前面所有的健
每次改变都是创建一个新的字典
2.访问字典
keys():访问键
values():访问值
items():访问一个项
3.get()
如果字典中不存在某个键值,正常调用会出现问题。
使用get()调用不会报错,其值会返回None。
4.setdefault()
和get类似
5.in
查找字典中是否存在某键,存在返回True,不存在返回False。
dict1 = {'one':'yi','two':'er'}print('three' in dict1) #False
6.clear():清空字典
7.copy():浅拷贝
dict1 = {'one':'yi','two':'er'}dict2 = dict1.copy()print(dict2) #{'two':'er','one':'yi',}dict3 = dict1print(dict3) #{'two':'er','one':'yi',}dict3['three'] = 'san'print(dict3) #{'three':'san','two':'er','one':'yi',}print(dict1) #{'three':'san','two':'er','one':'yi',}
8.pop():给出键,弹出对应的项
popitem():随机弹出某项
dict1 = {'one':'yi','two':'er','three':'san'}dict1.pop('one')print(dict1) #{'three':'san','two':'er'}
9.update():使用一个字典去更新另一个的内容
dict1 = {'one':'yi','two':'er','three':'san'}dict2 = {'three':'None','four':'si'}dict1.update(dict2)print(dict1) #{'four':'si','three':'None','two':'er','one':'yi'}
集合
- 使用大括号定义
- 具有元素唯一性,对于相同元素会自动剔除
- 不支持索引。
set1 = {1,2,3,4,4,5,8}set2 = {'one','one','two','three'}print(set1) #set([1, 2, 3, 4, 5, 8])print(set2) #set(['one', 'three', 'two'])set3 = set([1,2,2,3,3,5,6])print(set3) #set([1, 2, 3, 5, 6])
阅读全文
0 0
- Python学习——字典和集合
- Python学习(三)——字典、有序字典、集合
- python学习11-集合和字典
- python学习-集合、字典
- python字典和集合
- Python字典和集合
- Python字典和集合
- Python字典和集合
- **PYTHON** 字典和集合
- Python字典和集合
- Python学习笔记(四)—列表(list)、元组(tuple)和字典(dictionary)、集合(set)
- python学习笔记(4)——字典与集合
- python核心编程(七)—字典和集合
- Python学习笔记7:Python字典和集合
- iOS开发学习第十八课——字典 和 集合
- Python 学习笔记 -- 变量、元组、列表、字典和集合
- 02-python学习笔记:字典dict和集合set
- python练习题--字典和集合
- 事务的概述
- CodeForces
- 浅谈UML的概念和模型之UML视图
- java匿名内部类
- HDU
- Python学习——字典和集合
- 循环双向链表
- java:<创建一个MyInteger类>
- JS 本地存储布尔值Bug笔记
- 浅谈UML的概念和模型之UML类图关系
- XML封装通讯接口
- linux服务器上部署多个tomcat
- hust 1607 Triangles
- HBase - 数据写入流程解析