一、字典
1、概念及內存圖
列表:由一系列變量組成的可變序列容器
字典:由一系列鍵值對組成的可變散列容器
字典優勢:利用(內存)空間,換取(CPU查找)時間
? ? ? ?鍵key? 必須唯一且為不可變數據(字符串,數字,元組),若相同,第二個相同的key覆蓋第一個(通過不可變保證唯一性)
? ? ? 值value 沒有限制
2、基本操作
(1)創建
# 列表善于存儲單一緯度數據
list_name = ["麗麗","紅紅","嘿嘿"]
list_age = [20, 54, 56]
list_sex = ["女", "男", "女"]
# 字典善于存儲多個維度數據
# 創建方法1:字典名 = {鍵1:值1,鍵2:值2}
dict_ll = {"name":"麗麗", "age":"20", "sex":"女"} dict_hh= {"name":"紅紅", "age":"54", "sex":"男"} dict_hs = {"name":"嘿嘿", "age":"56", "sex":"女"}
創建方法2:字典名 = dict (容器)
# 需要保質容器的每個元素必須能一分為二
list_name = ["麗麗","紅紅","嘿嘿"]
print(dict(list_name))
(2)添加
添加,其實就是修改(如果key在,就是修改,如果key不在,就是添加)
添加方法:字典名[鍵] = 值
dict_ll = {"name":"麗麗", "age":"20", "sex":"女"}
dict_ll["money"] = 10000
# 定位快,修改
dict_ll["age"] = 26
# 讀取,先判斷,再讀取 print(dict_ll["age"])
注意:dict中根據key找value,直接定位,?字典名[鍵]
? ? ? ? ? ? ? ? ? ? ?根據value找key,則需要一一遍歷
(3)刪除
del 字典名[鍵1],字典名[鍵2]? 刪除后鍵值對同步消失
(4)遍歷
dict_ll = {"name":"麗麗", "age":"20", "sex":"女"} # 所有key for key in dict_ll:print(key) ''' name age sex ''' # 所有key for key in dict_ll.keys():print(key) ''' name age sex '''# 所有value for value in dict_ll.values():print(value) ''' 麗麗 20 女 ''' # 所有鍵和值 for item in dict_ll.items():print(item) ''' ('name', '麗麗') ('age', '20') ('sex', '女') ''' # 等價于 for key,value in dict_ll.items(): # 上述的拆包print(key,value) ''' name 麗麗 age 20 sex 女 ''' # 默認打印只有key值 print(dict_ll) #['name', 'age', 'sex'] print(dict_LL.items())
3、列表list和字典dict互相轉換
dict_ll = {"name":"麗麗", "age":"20", "sex":"女"} # dict轉list print(list(dict_ll.items())) # [('name', '麗麗'), ('age', '20'), ('sex', '女')] # list轉dict print(dict([('name', '麗麗'), ('age', '20'), ('sex', '女')])) # {'name': '麗麗', 'age': '20', 'sex': '女'
4、練習
# 疫情信息
list_epidemic = [{"region": "臺灣", "new": 16,"now": 2339, "total": 16931,},{"region": "陜西", "new": 182,"now": 859, "total": 1573,},{"region": "浙江", "new": 2,"now": 505, "total": 2008,},
]
# --打印所有疫情信息
for i in range(len(list_epidemic)):print(list_epidemic[i]["region"])print(list_epidemic[i]["new"])# 優化
for item in list_epidemic:print(item["region"])print(item["new"])# --查找新增人數大于10的地區名稱(將結果存入新列表)
new_list = []
for i in range(len(list_epidemic)):if list_epidemic[i]["new"]>10:new_list.append(list_epidemic[i]["region"])
print(new_list)# 優化
new_list = []
for item in list_epidemic:if item["new"] > 10:new_list.append(item["new"])
# --查找現有人數最大的地區信息(結果為字典)
max = list_epidemic[0]["now"]
flag = 0
for i in range(0,len(list_epidemic)):if max <= list_epidemic[i]["now"]:max = list_epidemic[i]["now"]flag = i
print(list_epidemic[flag])
list_epidemic = [{"region": "臺灣", "new": 16,"now": 2339, "total": 16931,},{"region": "陜西", "new": 182,"now": 859, "total": 1573,},{"region": "浙江", "new": 2,"now": 505, "total": 2008,},
]
# --根據現有人數對疫情信息降序(大->小)排列
for i in range(len(list_epidemic)):for j in range(i+1,len(list_epidemic)):if list_epidemic[i]["now"] < list_epidemic[j]["now"]:list_epidemic[i],list_epidemic[j]=list_epidemic[j],list_epidemic[i]
二、容器小結
1、種類與特征
????????字符串:存儲字符編碼(a-97),不可變,序列
????????列表list:存儲變量(地址),可變,序列
????????元組tuple:存儲變量(地址),不可變,序列
????????字典dict:存儲鍵值對,可變,散列
# 字典想拿到第一個鍵值對 轉換為列表/元組
dict_ll = {"name":"麗麗", "age":"20", "sex":"女"}
list_key = list(dict_ll()) # 拿到的只有鍵
print(list_key)
key = list_key[0]
value = dict_ll[key]list_item = list(dict_ll.items())
print(list_item[0])# 轉成元組更好,省內存
tuple_item = tuple(dict_ll.items())
print(tuple_item[0])
2、Python語言有哪些數據類型
????????可變類型:預留空間+自動擴容
??? ????????如:列表list,字典dict
??? ????????優點:操作數據方便(能夠增刪改)
??? ????????缺點:占用內存太大
? ? ? ? 不可變類型:按需分配
??? ????????如:int,float,bool,str,tuple
??? ????????優點:占用內存小
??? ????????缺點:不能適應現實的變化
3、序列與散列
????????序列:支持索引切片,定位數據靈活
????????散列:通過鍵定位數據,速度最快
4、語法
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?列表? ? ? ? ? ? ? ? ? ? ? ? ? ? ?字典
?? 創建
??????? 列表名=[數據1,數據2]? ? ? ? ? ? ? ? ? ? 字典名={鍵1:值1,鍵2:值2}
??????? 列表名=list(容器)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 字典名=dict(容器)
?? 添加
??????? 列表名.append(元素)? ? ? ? ? ? ? ? ? ? ? ? 字典名[鍵]=值? 不可變數據才可以當鍵
??????? 列表名.insert(索引,元素)
?? 定位
??????? 列表名[整數]? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 字典名[鍵]
??????? 列表名[開始:結束:間隔]
?? 刪除
???????? del 列表名[索引或切片]? ? ? ? ? ? ? ? ? ? del 字典名[鍵] ,鍵值都刪除
???????????????? 注意索引越界
???????? 列表名.remove(數據)
???????????????? 注意數據必須存在于列表中
?? 遍歷
??????? for item in 列表名:? ? ? ? ? ? ? ? ? ? ? ? ? ? for key in 字典:
??????? for i range(len(列表名)):? ? ? ? ? ? ? ? ? ?for value in 字典.values():
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?for k,v in 字典.items():?
三、練習1
# 2. 在終端中獲取顏色(RGBA),打印描述信息,
# 否則提示顏色不存在
# "R" -> "紅色"
# "G" -> "綠色"
# "B" -> "藍色"
# "A" -> "透明度"
dict_rgb = {"R":"紅色", "G":"綠色", "B":"藍色", "A":"透明度"}
input_rgb = input("請輸入顏色:")
if input_rgb in dict_rgb:print(dict_rgb[input_rgb])
else:print("不存在")# 3. 將列表中的數字累減
list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
sum_last = list02[0]
for i in range(1, len(list02)):sum_last -= list02[i]
print(sum_last)# 4. 在列表中查找最大值(不使用max,自定義算法實現)
# 思路:
# 假設第一個元素就是最大值
# 依次與后面元素進行比較
# # 如果發現更大值,則替換
list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
max = list02[0]
for item in list02:if max < item:max = item
print(max)# 5. (選做)彩票:雙色球
# 紅色:6個 1--33之間的整數 不能重復
# 藍色:1個 1--16之間的整數
# 1) 隨機產生一注彩票(列表(前六個是紅色,最后一個藍色))
# 2) 在終端中錄入一支彩票
# 要求:滿足彩票的規則.
import random
list_lottery = []
for i in range(6):num = random.randint(1,33)while num in list_lottery:num = random.randint(1, 33)list_lottery.append(num)
list_lottery.append(random.randint(1,16))# 優化
import random
list_lottery = []
while len(list_lottery) < 6:num = random.randint(1, 33)if num not in list_lottery:list_lottery.append(num)
list_lottery.append(random.randint(1,16))# 2) 在終端中錄入一支彩票
# 要求:滿足彩票的規則.
list_lottery = []
i = 1
while i <= 6:num = int(input(f"請錄入紅色第{i}注彩票:"))if 1 < num < 33:if num not in list_lottery:list_lottery.append(num)i += 1else:print("不能重復,請重新輸入")else:print("您輸入的數字超出范圍1-33,請重新輸入")while True:num2 = int(input(f"請錄入藍色第{i}注彩票:"))if 1 < num2 < 6:list_lottery.append(num2)breakelse:print("您輸入的數字超出范圍1-6,請重新輸入")
print(f"下注為{list_lottery}")