1. 程式人生 > >day16 python-04 字典

day16 python-04 字典

尋找 get 邏輯 discard size date super ren mov

Python之路,Day3 = Python基礎4

 1 # is  比較id
 2 
 3 # ==  比較數值
 4 
 5 # type(1) is type(2)   比較兩個變量的類型是否相同
 6 a = 1
 7 b = 1
 8 c = 1
 9 print(type(a), type(b), type(a) is type(b))     # <class ‘int‘> <class ‘int‘> True
10 print(type(a), type(c), type(a) is type(c))     # <class ‘int‘> <class ‘str‘> False
11 12 # 字典: 13 # 賦值方式 14 # dict(x=1,y=2,z=3) 15 # dict([(‘x‘,1), (‘y‘,2), (‘z‘,3)]) 16 17 d1 = {x:1, y:2, z: 3} 18 d2 = dict(x=1,y=2,z=3) 19 d3 = dict([(x,1), (y,2), (z,3)]) 20 print(d1) # {‘y‘: 2, ‘x‘: 1, ‘z‘: 3} 21 print(d2) # {‘y‘: 2, ‘x‘: 1, ‘z‘: 3} 22 print(d3) # {‘y‘: 2, ‘x‘: 1, ‘z‘: 3}
23 24 # {}.fromkeys([‘name‘, ‘age‘],None) None的位置,視為一個整體,分別給每一個 25 d4 = {}.fromkeys([name, age,sex],None) # {‘age‘: None, ‘sex‘: None, ‘name‘: None} 26 print(d4) 27 28 29 # d.clear() :清空字典中的元素 30 d1.clear() 31 print(d1) # {} 32 33 34 # d.get() :找元素,找不到返回None,可以d.get(‘y‘,‘找不到。。。‘)
35 print(d2.get(x)) # 1 36 print(d2.get(a)) # None 37 38 # d.items() 39 print(d2.items()) # dict_items([(‘x‘, 1), (‘z‘, 3), (‘y‘, 2)]) >>>可叠代 40 41 # d.keys() 42 print(d2.keys()) # dict_keys([‘z‘, ‘x‘, ‘y‘]) >>>可叠代 43 44 # d.values() 45 print(d2.values()) # dict_values([3, 1, 2]) >>>可叠代 46 47 # d.popitems() # 這個是隨機刪除一組(key:value)元素 48 print(d2.items()) # dict_items([(‘z‘, 3), (‘y‘, 2), (‘x‘, 1)]) >>>可叠代 49 50 # d.pop() :d.pop(‘z‘,‘沒有這個元素‘),後面加默認值,則不報錯 51 print(d2.pop(x)) # 1 52 53 # d.setdefult() :沒有就添加,有就不添加,返回存在的value 54 d2.setdefault(x,50) 55 print(d2) # {‘y‘: 2, ‘x‘: 50, ‘z‘: 3} 56 57 # d.update(d1) 58 print(d3,d4) # {‘y‘: 2, ‘z‘: 3, ‘x‘: 1} {‘name‘: None, ‘sex‘: None, ‘age‘: None} 59 d3.update(d4) 60 print(d3) # {‘y‘: 2, ‘z‘: 3, ‘x‘: 1, ‘name‘: None, ‘sex‘: None, ‘age‘: None} 61 62 63 # in 邏輯判斷,查看元素是否在字符串、列表、字典的key中等。。 64 # 65 # 自帶布爾值 66 # 所有數據自帶布爾值,有當數據為0、None、空的時候為False 67 # 68 # 69 # 集合 -- 關系運算 & 去重 70 # 元素必須是唯一的。 71 # s = set() :定義 72 # 元素為可哈希的 73 # 元素為無序的 74 # 循環: 75 # for i in s: 76 # print(i) 77 # 交集: 78 # s1 & s2 79 # s1.intersection(s2) 80 # 並集: 81 # s1 | s2 82 # s1.union(s2) 83 # 差集: 84 # s1 - s2 85 # s1.difference(s2) 86 # s1.difference_update(s2) # 尋找後,進行修改 87 # 對稱差集 88 # s1 ^ s2 89 # s1.smmetric_difference(s2) 90 # s1.update(s2) 91 # s1.add(‘1‘) :添加 92 # s1.discard(‘1‘) :刪除--不報錯 93 # s1.remove(‘1‘) :刪除--會報錯 94 # s1.pop() :隨機刪除 95 # s1.issubset(s2) :判斷子集 96 # s1.issuperset(s2) :判斷為父集 97 # s1.disjoint(s2) :兩個集合沒有交集,返回True

day16 python-04 字典