4.2 字典(Dictionary)
4.2.1 特点
- 采用键值对的形式(key:value)表示
- key不可以重复,value可以重复
- 可变数据,改变值其储存空间不变
4.2.2 创建
{}
Dict dict(key1=value1,.....)
函数-
Dict dict.fomKeys([key1,key2,....],default_value=None)
dictionary1={“name”:"Jack","sex":"male","age":25} type(dictionary1) --> <class 'dict'> dictionary1 --> {'name': 'Jack', 'sex': 'male', 'age': 25} dictionary2=dict.fromkeys(["name","sex","age"],"unknown") type(dictionary2) --> <class 'dict'> dictionary2 --> {'name': 'unkonown', 'sex': 'unkonown', 'age':'unknown'}
4.2.3 取值(查)
value Dict[key]
-
value Dict.get(key[,default_value])
dictionary={“name”:"Jack","sex":"male","age":25} dictionary["name"] --> 'Jack' dictinnary["grade"] --> NameError dictionary.get("name") --> 'Jack' dictionary.get("grade") --> dictionary.get("grade","unkonwn") --> 'unknown'
4.2.4 字典遍历
-
for key in Dict:\n ......
dictionary={"name":"Jack","age":"25"} for key in dictionary: print(key,"---",dictionary[key]) Result: name --- Jack age --- 25
-
for key,value in Dict.items():\n ......
dictionary={"name":"Jack","age":"25"} for key,value in dictionary.items(): print(key,"---",value) Result: name --- Jack age --- 25
4.2.5 字典的增删改操作
Dict[key]=new_value
void Dict.update({key1:new_value1,key2:value2,.....})
增操作与改操作相同,有则更新,无则增加(上面两种方法都可以)
value Dict.pop(key)
--> 删除key对应的一项Tuple Dict.popitem()
--> 删除最后一项-
void Dict.clear()
--> 清空字典dict={"name":"Jack","sex":"male","age":"25"} dict --> {'name': 'Jack', 'sex': 'male', 'age': '25'} dict["job"]="police" #1 dict --> {'name': 'Jack', 'sex': 'male', 'age': '25', 'job': 'police'} dict["age"]=25 #3 dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police'} dict.update({"dpt":"indentification","sal":5000}) #2 dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police', 'dpt': 'indentification', 'sal': 5000} dict.pop("dpt") --> 'indentification' #4 dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police', 'sal': 5000} dict.popitem() --> ('sal', 5000) #5 dict --> {'name': 'Jack', 'sex': 'male', 'age': 25, 'job': 'police'} dict.clear() #6 dict --> {}
4.2.5 字典的其它操作
value Dict.setdefault(key,value)
--> 设置默认值,如果key存在,可以忽略Dict_keys Dict.keys()
Dict_values Dict.values()
Dict_items Dict.items()
2、3、4都是获取字典视图,字典变化,视图变化
老版本字典格式化字符串
“%(key1)s,%(key2)s" %Dict
-
python3之后字典格式化字符串
“{key1},{key2}”.format_map(Dict)
dict={"name":"Jack","sex":"male","age":"25"} dict["dept"] --> KeyError dict.setdefault("deft","None") --> 'None' dict["dept"] --> KeyError type(dict.keys) --> <class 'builtin_function_or_method'> type(dict.values) --> <class 'builtin_function_or_method'> type(dict.items) --> <class 'builtin_function_or_method'> print("%(name)s--%(age)s"%dict) --> Jack--25 print("{name}--{age}".format_map(dict)) --> Jack--25
4.2.5 散列值(Hash)和字典的储存原理
-
int hash(value)
--> 在多次运行时,数据是不一样的 - 字典储存原理:将Key先转换为Hash值,再在对应内存空间中放入Value。内存地址==Key Hash值。所以,字典中储存数据不是按顺序来。
- 字典在内存中不连续储存,列表连续储存。
4.2.5 应用
- 在C++课设中,房间信息可以用字典来储存
5. 元组与集合
5.1 元组(Tuple)
5.1.1介绍
- Tuple是不变List,创建之后不能修改,只能创建,本身元素只能查操作(元组中有列表,则列表中数据可以写),且查操作与List相同
- Tuple使用()
5.1.2 元组运算符
Tuple3=Tuple1+Tuple2
Tuple2=Tuple*count
-
元组运算符适用于列表,但是前后类型应该相同
[1,2,3]+[4,5,6] --> [1, 2, 3, 4, 5, 6] [1,2,3]*3 --> [1, 2, 3, 1, 2, 3, 1, 2, 3] (1,2,3)+(4,5,6) --> (1, 2, 3, 4, 5, 6) (1,2,3)*2 --> (1, 2, 3, 1, 2, 3) (1,)*2 --> (1, 1) (1)*2 --> 2 [1]*2 --> [1, 1]
5.1.2 元组创建
- (element,…….)
- element,……..
- 元组只有一个元素时,元素后面必须要有逗号,否则视为普通括号中的其它数据
5.1.3 列表与元组的区别和应用
- 内容:List内存中内容可以改变,Tuple内存中内容不可改变
- 内存:List内存动态变化,Tuple内存固定不变
- 效率:List效率低,Tuple效率高
- 使用:List用于保存运行时需要变化的数据,Tuple用于保存不用改变的数据
5.2 序列
5.2.1 介绍
- 序列中元素是有序的
- 序列是有索引的
- String、List、Tuple、Range(数字序列)都是序列,是数据结构的统称
5.2.2 数字序列的创建
-
Range range(begin_num,edn_num[,step])
range(1,4) --> range(1,4) range(1,10,2) --> range(1,10,2)
5.2.3 Range遍历其它序列和应用
- 遍历String
- 遍历List
- 遍历Tuple
- 质数
5.2.3 序列类型互相转换
List list(sequence)
--> 转换为列表Tuple tuple(sequence)
--> 转换为元组String element.join(String_Tuple/List)
String str()
--> 转换为字符串List String.split(element)
--> 传入分割元素,分割String,返回ListList String.splitlies()
--> 按行分割String-
for循环
--> 辅助使用,将数字转换为String#转换为List #1,4,5 list((1,2,3,4)) --> [1, 2, 3, 4] list("abcd") --> ['a', 'b', 'c', 'd'] list(range(0,11,2)) --> [0, 2, 4, 6, 8, 10] "1,2,3,4".split(",") --> ['1', '2', '3', '4'] "1\n2\n3\n4".splitlines() --> ['1', '2', '3', '4'] #转换为Tuple #2 tuple("hello") --> ('h', 'e', 'l', 'l', 'o') tuple([1,2,3]) --> (1, 2, 3) tuple(range(1,5)) --> (1, 2, 3, 4) #转换为String #使用到join()函数 #3 ",".join("hello") --> 'h,e,l,l,o' ",".join(("a","b","c")) --> 'a,b,c' ",".join(["a","b","c"]) --> 'a,b,c' "".join(("a","b","c")) --> 'abc' "".join(["a","b","c"]) --> 'abc' #使用str()函数 #3 str(["a","b","c"] --> "['a', 'b', 'c']" str(range(1,5)) --> 'range(1, 5)' str(("a","b")) --> "('a', 'b')" #range()-->String #6 string = "" for i in range(1,5): string+=str(i) string --> '1234'
5.3 集合(Set)
5.3.1 介绍
- 集合是没有value的字典,可以参考数学中集合
- 无序性、互异性
- 可变数据类型、允许数学运算、分散储存
- 集合生成Hash,Hash内存储存数据
5.3.2 集合的创建
{}
Set set(anthor_type(Tuple/String/List))
-
空集合的创建不能用{},应该用
set()
dict={} type(dict) --> <class 'dict'> set=set() type(set) --> <class 'set'> set={1,2,3} set((1,2,3)) --> {1,2,3} set([1,2,3]) --> {1,2,3} set("hello") --> {'l', 'o', 'e', 'h'} set(range(1,6)) --> {1, 2, 3, 4, 5}
5.3.3 集合的数学运算(交集、并集、差集)
Set Set1.intersection(Set2)
Set set1&set2
--> 交集void Set1.intersection_update(Set2)
Set Set1.union(Set2)
Set set1|set2
--> 并集--> 不存在void Set1.union(Set2)
Set Set1.difference(Set2)
差集(Set1中Set2不存在的元素)Set set1-set2
--> 差集Set Set1.symmetric_difference(Set2)
--> 双向差集,两个集合中都不存在的元素void Set1.difference_update(Set2)
void Set1.symmetric_difference_update(Set2)
-
set1,set2
--> 两个Set合成为一个Tupleset1={1,2,3,4,5} set2={4,5,6,7,8} #交集 set1.intersection(set2) --> {4, 5} #1 set1&set2 --> {4, 5} #2 set1.intersection_update(set2) #3 set1 --> {4, 5} #并集 set1={1,2,3,4,5} set1.union(set2) --> {1, 2, 3, 4, 5, 6, 7, 8} #4 set1|set2 --> {1, 2, 3, 4, 5, 6, 7, 8} #5 #差集 set1.difference(set2) --> {1, 2, 3} #7 set1-set2 --> {1, 2, 3} #8 set1.symmetric_difference(set2) --> {1, 2, 3, 6, 7, 8} #9 set1.difference_update(set2) #10 set1 --> {1,2,3} set1={1,2,3,4,5} set1.symmetric_difference_update(set2) #11 set1 --> {1, 2, 3, 6, 7, 8} #合并为tuple set1={1,2,3,4,5} set2={4,5,6,7,8} st1,set2 --> ({1, 2, 3, 4, 5}, {4, 5, 6, 7, 8}) #12
5.3.4 集合间的关系操作
Bool Set1==Set2
Bool Set1.issubset(Set2)
--> Set1是不是Set2的子集Bool Set1.issuperset(Set2)
--> Set1是否为Set2的父集-
Bool Set1.isdisjoint(Set2)
--> Set1和Set2中是否有重复元素# 2 set1={1,2} set2={1,2,3} set1.issubset(set2) --> True set1={1,2,5} set1.issubset(set2) --> False # 3 set1={1,2,3,4} set2={2,3} set1.issuperset(set2) --> True set2={7,8} set1.issuperset(set2) --> False # 4 set1={1,2,3,4,5} set2={6,7,8,9} set1.isdisjoint(set2) --> True set1={6,7} set1.isdisjoint(set2) --> False
5.3.5 集合的增删
void Set1.add(element)
void Set1.update(Tuple/List/Dict)
不可直接改
void Set.remove(element)
--> 不存在报错-
void Set.discard(element)
--> 不存在不报错set1={1,2,3,4,5} set1.add(0) #1 set1 --> {0, 1, 2, 3, 4, 5} set1={1,2,3,4,5} set1.update([6,7,8]) #2 set1 --> {1, 2, 3, 4, 5, 6, 7, 8} set1={1,2,3,4,5} set1.update((6,7,8)) #2 set1 --> {1, 2, 3, 4, 5, 6, 7, 8} set1={1,2,3,4,5} set1.update({6,7,8}) #2 set1 --> {1, 2, 3, 4, 5, 6, 7, 8} set1={1,2,3,4,5} set1.update(range(10,16)) #2 set1 --> {1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15} set1={1,2,3,4,5} set1.remove(1) #4 set1 --> {2, 3, 4, 5} set1.remove(0) -->KeyError #4 set1 --> {1,2,3,4,5} set1.discard(1) #5 set1 --> {2, 3, 4, 5} set1.discard(0) #5
5.4 内置生成式
-
列表生成式
List=[i*10 for i in range(10,20)... if i%2 == 0...]
list=[i*j for i in range(1,5) for j in range(1,5) if i%2==0] list Result: [2, 4, 6, 8, 4, 8, 12, 16]
-
字典生成式
Dict={i*10 for i in range(10,20)... if i%2 == 0...}
fruits=["apple","banana","orange"] dict={i:fruits[i] for i in range(0,len(fruits))} dict Result: {0: 'apple', 1: 'banana', 2: 'orange'}
-
集合生成式
Set={i*10 for i in range(10,20)... if i%2 == 0...}
set={i*j for i in range(1,5) for j in range(1,5) if i%2==0} set Result: {2, 4, 6, 8, 12, 16}