1、dict字典數(shù)據(jù)類型
字典數(shù)據(jù)類型、map數(shù)據(jù)類型(映射類型)、容器數(shù)據(jù)類型,具有key-value鍵值對,key具有唯一性,不可改變
定義:demo_dict = {}? ?或? demo_dict = {"name": "tom", "age": 18}
a_dict = dict.formkeys([1,2,3], "hello")
取數(shù)據(jù):
print(demo_dict["name"])? ? ?# 通過key取得value的值,如果獲取一個不存在的key,會報(bào)錯,KeyError
demo_dict["name"] = "joy"? ?#? 如果key存在,則是修改key對應(yīng)的value的值,如果不存在,則是向字典中添加新的數(shù)據(jù)項(xiàng)
字典的遍歷:
遍歷所有數(shù)據(jù):
for item in demo_dict.items():
? ? print(item)
key關(guān)鍵字的遍歷:
for key in demo_dict.keys():
? ? print(key)
value的遍歷:
for value in demo_dict.values():
? ? print(value)
如何判斷指定的key是否存在于字典中:
print("sex" in demo_dict)
print(demo_dict.__contains__("addr"))
版本區(qū)別:
py2:? demo_dict.has_key("name")
py3:? in關(guān)鍵字
其他操作:
刪除數(shù)據(jù)項(xiàng)操作:
demo_dict.pop("name")? ?# 通過key來刪除
demo_dict.popitem()? ?# 沒有參數(shù),隨機(jī)刪除一個數(shù)據(jù)項(xiàng)
清空字典:
demo_dict.clear()
復(fù)制(副本):
d_dict = demo_dict.copy()
修改字典:
demo_dict["name"] = "tom"? #? 如果存在則為修改,不存在為添加
demo_dict.setdefault("name", "jim")? # 第一個參數(shù)為key,第二個參數(shù)為默認(rèn)值(如果不存在)
更新:
a_dict = {"sex": "男", "addr": "北京"}
demo_dict.update(a_dict)
2、set集合數(shù)據(jù)類型
set集合數(shù)據(jù)類型和字典數(shù)據(jù)類型相比,set沒有value值,set中的元素不能重復(fù)
定義:
a_set = set()
b_set = {1,2,3}
添加元素:
a_set.add(2)
a_set.update(b_set)
刪除元素:
a_set.remove(2)
清空:
a_set.clear()
不可變集合:
num_set = frozenset([1,2,3,4])? ?#? 不可變集合,不能添加,刪除,清空元素,可以復(fù)制
集合間的運(yùn)算:
print(2 in a_set)? # 判斷某個元素是否存在? not in? 不在
print(a_set != b_set)? ?# 不等于
print(a_set >= b_set)? #?
print(a_set & b_set)? ?# 求交集
print(a_set | b_set)? ?# 求并集
print(a_set - b_set)? ?# 求差集
print(a_set - b_set)? ?# 大數(shù)減小數(shù)
print(a_set ^ b_set)? ?# 異或運(yùn)算
3、list/dict/set的區(qū)別
①、查找元素速度
list元素較多時(shí),查找速度會隨著元素的個數(shù)增多而減慢,而dict不會,所有順序由關(guān)鍵字key來決定,查找速度接近一個恒定值
②、內(nèi)存
list占用內(nèi)存空間小,dict占用空間大
③、其他
list中的元素可以重復(fù),dict里面的key是不能重復(fù)的,set元素不能重復(fù),重復(fù)會發(fā)生覆蓋