python学习(三)
1 字典
字典是一个可变的、无序的容器,是python中唯一内置的映射类型的数据结构
字典中的元素都是键值对(item项),每一个值(value)都对应一个键(key),标准性符合是{}和;
注意
- 字典的键不可以出现重复,值是可以重复的
- 必须是不可变的数据类型才可以做字典的键
1.1 字典定义
直接用键值和{}来定义
例如,
输入In:
dict_sale = {"小乔":221073,"大乔":211502,"周瑜":466296}
dict_sale
输出Out:
{'周瑜': 466296, '大乔': 211502, '小乔': 221073}
输入In:
len(dict_sale)
输出Out:
3
1.2 通过dict函数来创建字典
例如:
输入In:
dict() #生成空字典
输出Out:
{}
输入In:
dict(one = 1,two = 2)
输出Out:
{'one': 1, 'two': 2}
输入In:
list1 = [["a",1],["b",2],["c",3]] dict(list1)
输出Out:
{'a': 1, 'b': 2, 'c': 3}
1.3 结合zip函数创建字典
例子:
输入In:
list(zip(list("abcde"),(1,2,3,4,5))) #生成列表
输出Out:
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
输入In:
dict(zip(list("abcde"),(1,2,3,4,5))) #生成字典
输出Out:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
输入In:
list("abcde")
输出Out:
['a', 'b', 'c', 'd', 'e']
1.4 字典的特征
输入In:
dict_sale
输出Out:
{'周瑜': 466296, '大乔': 211502, '小乔': 221073}
输入In:
dict_sale["周瑜"]
输出Out:
466296
输入In:
dict_sale["周瑜"] += 20000
dict_sale["周瑜"]
输出Out:
486296
1.5 字典的常用方法
1.5.1 增加
输入In:
dict_sale["孙权"] = 420000 #在字典中增加
dict_sale
输出Out:
{'周瑜': 486296, '大乔': 211502, '孙权': 420000, '小乔': 221073}
1.5.2 删除
输入In:
del dict_sale["小乔"]
dict_sale
输出Out:
{'周瑜': 486296, '大乔': 211502, '孙权': 420000}
输入In:
dict_sale.pop("大乔") #大乔同学离职,返回被删除的键值对应的值
输出Out:
211502
输入In:
dict_sale
输出Out:
{'周瑜': 486296, '孙权': 420000}
输入In:
dict_sale.popitem() #删除并返回最后一对键值对
输出Out:
('孙权', 420000)
输入In:
dict_sale
输出Out:
{'周瑜': 486296}
输入In:
#解散所有员工 dict_sale.clear()
dict_sale
输出Out:
{}
输入In:
del dict_sale
dict_sale #删除字典了,所以报错,报错信息如下:
输出Out:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-31-319fcc0b91b2> in <module>() ----> 1 dict_sale #删除字典了,所以报错 NameError: name 'dict_sale' is not defined
1.5.3 查找
输入In:
dict1 = dict(zip(["a","b","c"],(1,2,3)))
dict1
输出Out:
{'a': 1, 'b': 2, 'c': 3}
输入In:
"a" in dict1
输出Out:
True
输入In:
3 in dict1
输出Out:
False
输入In:
dict1.get("c")
输出Out:
3
输入In:
dict1.get("a","没有这个关键字")
输出Out:
1
1.5.4 查看字典的关键字
输入In:
dict1
输出Out:
{'a': 1, 'b': 2, 'c': 3}
输入In:
dict1.values()
输出Out:
dict_values([1, 2, 3])
输入In:
dict1.keys()
输出Out:
dict_keys(['a', 'b', 'c'])
输入In:
dict1.items()
输出Out:
dict_items([('a', 1), ('b', 2), ('c', 3)])
1.5.5 例子
- 计算平均值
输入In:
dict2 = {"小红" : 85,"小敏" : 92,"小丽" : 88} #求三人的平均值
dict2
输出Out:
{'小丽': 88, '小敏': 92, '小红': 85}
方案:
输入In:
#循环方法 for i in dict2.values(): print(i)
输出Out:
85
92
88
输入In:
s = 0 for i in dict2.values(): s += i print("所有同学的平均分是{:.2f}".format(s/len(dict2)))
输出Out:
所有同学的平均分是88.33
2 集合
集合是一种无序的可变的容器,对应于数学中的集合,标志性符号是{}
集合中没有重复值,集合中的元素值必须是不可变的数据类型
2.1 集合定义
例如:
输入In:
set1 = {1,2,3,4}
set1
输出Out:
{1, 2, 3, 4}
输入In:
type(set1)
输出Out:
set
2.2 通过set函数定义集合
例如:
输入In:
set2 = set(["1","2","3"])
set2
输出Out:
{'1', '2', '3'}
输入In:
list3 = list("abcdeabc")
list3
输出Out:
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c']
输入In:
#去除list3中重复的元素 set(list3)
输出Out:
{'a', 'b', 'c', 'd', 'e'}
输入In:
list(set(list3))
输出Out:
['b', 'd', 'a', 'e', 'c']