列表補充
補充方法
清空列表 clear
# clear 清空列表 l = [1, 2, 3, 4, 4] print(l.clear()) # clear沒有返回值(None) print(l) # None # []
統計列表中指定元素出現的次數 count
# count 統計一個元素在列表中出現了幾次 l = [1, 2, 3, 4, 4] print(l.count(4)) # 2
列表反向、排序 reverse sort(帶參數,可指定按正序/ 反序排)
# reverse 將列表翻轉 l = [1, 2, 3, 4, 4, 2] print(l.reverse()) # reverse沒有返回值(None) print(l) # None # [2, 4, 4, 3, 2, 1] # sort 排序,默認從小到大排序 l = [1, 2, 3, 4, 4, 2] print(l.sort()) # sort沒有返回值(None) print(l) # None # [1, 2, 2, 3, 4, 4] l = [1, 2, 3, 4, 4, 2] print(l.sort(reverse=True)) # sort可以指定參數來確定排序規則 print(l) # None # [4, 4, 3, 2, 2, 1] l = list('dasb41564s5.*/-^&#$84') print(l.sort()) # sort方法排序字符時按ASCII碼排序 print(l) # None # ['#', '$', '&', '*', '-', '.', '/', '1', '4', '4', '4', '5', '5', '6', '8', '^', 'a', 'b', 'd', 's', 's']
總結
# ------- 列表總結 --------- # 能存多個值 # 有序的 # 可變類型
# 隊列:先進先出 (排隊)
# 堆棧:先進后出 (疊書、疊衣服 拿出來)
元組
簡介
# 作用:能存儲多個元素 # 定義:與列表一致,只不過把 [] 變成了 () # 特點: # 能存多個值 # 有序(能用索引取值) # 不可變:不可以修改元素的值,不可以增加元素個數,刪除元素個數 # 只能看不能改的場景,推薦用元組 # 存相同的數據,元組比列表占用的資源會更少(列表多出來的那堆方法也會占很多空間)
內置方法
定義元組
t = (1, 2, 3, 4) # tuple((1, 2, 3, 4)) print(type(t)) # <class 'tuple'> t = tuple(1) # 報錯,內部基於for循環,必須傳容器類型 print(type(t)) # 定義元組時如果只有一個元素,也得加上 , 逗號 不然會被python 解釋成 其他類型 t = (1) print(type(t)) # <class 'int'> t = (1, ) print(type(t)) # <class 'tuple'> t = ('a') print(type(t)) # <class 'str'> t = ('a', ) print(type(t)) # <class 'tuple'>
驗證是否可變類型 --->不可變類型
t2 = (1, 2, 3, [1, 2, 3]) print(id(t2)) # 2270010972424 t2[3][0] = 666666 print(t2) print(id(t2)) # (1, 2, 3, [666666, 2, 3]) # 注意這里改的是元組內部的列表的值,不是在改動元組(元組的第四個元素(索引為3),存的是個內存地址) # 2270010972424 # ---> 內存地址不變,所以他是不可變類型
索引取值
# 索引取值 可取不可改 t = (2, 3, 4) print(t[0]) # t[0] = 4 # 會直接報錯,TypeError: 'tuple' object does not support item assignment 元組的元素不可以改(如果元素是可變類型,那么可以改) t = (2, 3, 4, [5, 6, 7]) t[3][0] = '我改了' # 不報錯,因為改的是列表(具體看原理圖(內存指向,實際元組沒有改動)) print(t) # (2, 3, 4, ['我改了', 6, 7])
切片
# 切片 與列表字符串的用法一致,這里就不過多舉例了 t = (1, 3, 5, 8, 10) print(t[-1:-5:-1]) # (10, 8, 5, 3)
元組中的元素個數 len
# 元組中的元素個數 len t = (1, 3, 5, 8, 10) print(len(t)) # 5
成員運算 in / not in
# 成員運算 in / not in t = (1, 3, 5, 8, 10) print(3 in t) print(3 not in t) print(13 in t) print(13 not in t) # True # False # False # True
作為循環的迭代器對象 for in
# 作為循環的迭代器對象 for in t = (1, 3, 5, 8, 10) for i in t: print(i, end=' ') # 1 3 5 8 10
統計某個元素在元組中出現的次數 count
# count 統計某個元素在元組中出現的次數 t = ('hello', 'thank', 'you', 1, 1.1, ['hello', 3, 'thank'], 'thank', 'you', 'very', 'much') print(type(t)) print(t.count('hello')) # 元素內部不管,只管第一層 print(t.count('thank')) # <class 'tuple'> # 1 # 2
獲取元素的索引 index (找不到會報錯)
# index 獲取元素的索引(試試字符串類型的?) print(t.index('thank')) # 1 # print(t.index('your')) # 找不到值會報錯 ValueError: tuple.index(x): x not in tuple # 可以用count 判斷在不在里面(為0 則不在里面,為其他值則在),再用index 找該元素的索引
字典
簡介
# 能存儲多組 key: value 這樣的鍵值對,可存可取 # key是對value的描述,並且key 通常情況下都是字符串,其實這個key 只能是不可變類型,value可以是任意數據類型 # 字典的key 是唯一性標識,同一個字典中key 不能重復 # 如果重復了,只會按照最后一組鍵值對存儲(即覆蓋了前一組同名的 key) #
# 字典是無序的,它是按 key 取值,不是索引 # 字典是可變類型:鍵值對發生改變,字典的內存地址不會改變
# 數字類型(int、float),字符串,元組 都可以作為字典的 key
內置函數
定義字典
d = {'name': 'jason', 'password': 123} # d = dict({'name': 'jason', 'password': 123}) d1 = {1: '1', 0: '0', 1.1: '1.1', 'string': 'string', (1, 2): '到底行不行呢?'} print(d1) print(type(d1)) # {1: '1', 0: '0', 1.1: '1.1', 'string': 'string', (1, 2): '到底行不行呢?'} # <class 'dict'> # 沒錯,它也是一個合法的字典類型 print(d1[1]) print(d1[1.1]) print(d1['string']) print(d1[(1, 2)]) # 1 # 1.1 # string # 到底行不行呢? # 定義字典的三種方式 # 1 直接定義 d1 = {'name': 'jason', 'password': '123'} # 2 ----> 通過關鍵字傳參來定義 ***重點掌握(后期面向對象的時候好用)*** d2 = dict(name='jason', password=123, age=18) # 3 直接dict 類型轉換 l = [ ['name', 'jason'], ['age', 18], ['hobby', 'read'] ] # 簡便寫法 d3 = {} d3 = dict(l) print(d3) # {'name': 'jason', 'age': 18, 'hobby': 'read'} # 上面寫法的原理 d3 = {} for k, v in l: # ['name', 'jason'],['age', 18].... # 這里的 k,v 利用了解壓賦值 d3[k] = v print(d3) # {'name': 'jason', 'age': 18, 'hobby': 'read'}
創建字典的其他方式 fromkeys (不怎么好用)
# fromkeys() 用來創造字典 d1 = {'name': 'jaoon', 'password': '123', 'sex': 'gender', 'salary': 16000} print(d1.fromkeys('name')) # {'n': None, 'a': None, 'm': None, 'e': None} # 擴展用法 l = ['name', 'password', 'age', 'hobby'] dic = {} print(dic.fromkeys(l, 123)) # 快速創建字典,后續再去更改 # {'name': 123, 'password': 123, 'age': 123, 'hobby': 123} dic = {} l = ['name', 'password', 'age', 'hobby'] l2 = ["swb", 18, ["study", "cooking"]] print(dic.fromkeys(l, l2)) print(dic) # {'name': ['swb', 18, ['study', 'cooking']], 'password': ['swb', 18, ['study', 'cooking']], 'age': ['swb', 18, ['study', 'cooking']], 'hobby': ['swb', 18, ['study', 'cooking']]} # {}
給字典中的指定鍵值對指定默認值 setdefault
# setdefault() d1 = {'name': 'jaoon', 'password': '123'} print(d1.setdefault('name', 'xxoo')) # 當鍵存在的情況下會返回該鍵的值,並且不會改變該鍵的值 print(d1) print(d1.setdefault('age', 18)) # 當鍵不存在的情況下會給字典添加一個鍵值對(兩個參數),並且會把新增的鍵值對的值返回 print(d1) # jaoon # {'name': 'jaoon', 'password': '123'} # 18 # {'name': 'jaoon', 'password': '123', 'age': 18}
更新字典的值:1.字典的 update 方法,2.直接通過 不存在的key 賦值的方式添加鍵值對(具體看下方例子)
# 1.update() # 1.1 d1 = {'name': 'jaoon', 'password': '123'} d2 = {'age': 18} print(d1.update(d2)) print(d1) # None # {'name': 'jaoon', 'password': '123', 'age': 18} # 1.2 d1 = {'name': 'jaoon', 'password': '123'} print(d1.update(age=18)) print(d1) # None # {'name': 'jaoon', 'password': '123', 'age': 18} # 2 推薦直接這樣寫 -----------> !!!! 上面寫法太麻煩,不如這個好用 d1 = {'name': 'jaoon', 'password': '123'} print(d1) d1['age'] = 18 print(d1) # {'name': 'jaoon', 'password': '123'} # {'name': 'jaoon', 'password': '123', 'age': 18}
獲取字符串中鍵值對個數 len
dit2 = {'name': 'egon', 'name': 'jason', 'name': 'alex', 'age': 18} print(dit2) print(len(dit2)) # {'name': 'alex', 'age': 18} # 重復的鍵會覆蓋前面的鍵 # 2
成員運算 in / not in (只能取到key 值)
# 成員運算 in/ not in 字典在for循環只暴露出 key, value無法取到,不能做成員運算 d3 = {'name': 'jaoon', 'password': '123'} print('123' in d3) print('password' in d3) # False # True
按key 取值 (類似列表中的索引取值 ---> 字典是無序的,字典中沒有索引取值)
# 按key 存取值:可存可取 d3 = {'name': 'jaoon', 'password': '123'} print(id(d3)) # 2364215340992 print(d3['name']) # jaoon d3['name'] = 'egon' # 改的是指向,不是索引, 字典是無序的, key 重復了是替換的意思 d3['age'] = 18 # 賦值語句當key 不存在的情況下,會自動新增一個鍵值對 print(d3, id(d3)) # {'name': 'egon', 'password': '123', 'age': 18} 2364215340992
取值的其他方法 keys values items get
# 獲取字典value的方法 ----》 keys values items 在 python2.x 產生的是列表,而 python3.x 是生成器對象 # 1. 粗暴的循環獲取(通過key ) # 字典的 keys() values() items() 方法在 python 2.x 和 3.x 中有區別,像老母豬 # 2. keys() d1 = {'name': 'jaoon', 'password': '123', 'sex': 'gender', 'salary': 16000} print(d1.keys()) # dict_keys(['name', 'password', 'sex', 'salary']) ,像老母豬 for k in d1.keys(): print(k) # name # password # sex # salary # 3. values() 與上面類似 d1 = {'name': 'jaoon', 'password': '123', 'sex': 'gender', 'salary': 16000} print(d1.values()) # dict_values(['jaoon', '123', 'gender', 16000]) for i in d1.values(): print(i) # jaoon # 123 # gender # 16000 # 4. items() 列表套元組,元組的第一個元素是字典的key , 第二個元素是字典的value d1 = {'name': 'jaoon', 'password': '123', 'sex': 'gender', 'salary': 16000} print(d1.items()) # dict_items([('name', 'jaoon'), ('password', '123'), ('sex', 'gender'), ('salary', 16000)]) for i in d1.items(): print(i) # ('name', 'jaoon') # ('password', '123') # ('sex', 'gender') # ('salary', 16000) # 作為迭代器對象循環取值 # for i in ... # get() 根據key 獲取 value, 可以傳第二個參數,當傳入的key 不存在,會返回(提示信息)該參數, 存在則會返回該key 對應的值, 第二個參數不寫的話,key 不存在會返回None ,如果存在則會返回該key 對應的value # 推薦字典取值統一用 get ********** d1 = {'name': 'jaoon', 'password': '123', 'sex': 'gender', 'salary': 16000} print(d1.get('name')) # jaoon print(d1.get('hahah')) # 當key 不存在時不會報錯,返回None, 用 []取不存在的會直接報錯 # None print(d1.get('name', '你給我的name 不在字典的key 中')) print(d1.get('hahah', '你給我的hahah 不在字典的key 中')) # jaoon # 你給我的hahah 不在字典的key 中
刪除字典中的鍵值對或清空字典 del pop popitem clear
# 刪除 # del d3 = {'name': 'jaoon', 'password': '123'} del d3['name'] print(d3) # {'password': '123'} # pop 傳key, key 不存在會直接報錯 d3 = {'name': 'jaoon', 'password': '123'} print(d3.pop('name')) # pop 返回的是value print(d3) # jaoon # {'password': '123'} # print(d3.pop('age')) # 當鍵不存在的時候,直接報錯,KeyError: 'age' # popitem 不需要參數,彈出"最后"一個鍵值對(字典是無序的,不存在什么第幾個、最后一個) d3 = {'name': 'jaoon', 'password': '123'} print(d3.popitem()) print(d3) # ('password', '123') # {'name': 'jaoon'} print(d3.popitem()) # ('name', 'jaoon') # print(d3.popitem()) # 會報錯,彈空了 # clear 清空字典 d3 = {'name': 'jaoon', 'password': '123'} print(d3.clear()) print(d3) # None # {}
集合
簡介
# 群體之間作比較,不涉及單個元素 --> 推薦用集合 (見關系圖,整理到博客里去) # 作用: 做關系運算: 共同好友、共同粉絲 ---> 涉及到共同,兩個群體之間作比較 # 去重,把重復元素剔除掉 # 可以定義多個元素,元素之間用逗號分隔 # 集合的元素必須遵循的三個原則 # 1:每個元素必須是不可變類型(元素值改變后,內存地址是否會隨之改變) # 可變: 不可hash # 不可變: 可hash ''' d = {[1, 2]: 'name'} # 會報錯,不可hash,並且元素之間 , 間隔 TypeError: unhashable type: 'list' s = {1, 2, 1.1, 'string', (1, 2)} print('-----------', s) # ----------- {(1, 2), 1, 2, 1.1, 'string'} ''' # 2:沒有重復的元素 ''' s = {1, 2, 3, 3, 4, 3} # 自動將重復的元素去除 print(s) # {1, 2, 3, 4} 將其他類型去重成集合,再想辦法轉回去 l = ['jason', 'egon', 'jason'] s = set() print(s.update(l)) print(s) # None # {'egon', 'jason'} ''' # 3:無序 ''' s = {1, 2, 3, 4, 5} print(s[1]) # 會直接報錯,集合不支持索引取值 TypeError: 'set' object does not support indexing '''
內置函數
定義集合
# 定義集合 (跟字典很像,但它內部不是鍵值對) s = {1, 2, 3} # s = set({1, 2, 3}) print(type(s)) # <class 'set'> # 嘗試定義空集合 s = {} # 如果僅僅只寫了 {} .那么python 會默認把它當成字典類型 print(type(s)) # <class 'dict'> # 定義空集合 只能用關鍵字 set s = set() print(type(s)) # <class 'set'> # 定義空元組 就是本身的元組 t = () print(type(t)) # <class 'tuple'> # print(set(1)) # 會報錯,set也是迭代對象 TypeError: 'int' object is not iterable print(set((1,))) # {1}
向集合中添加元素 add
# 集合添加元素 # add s = {1, 2, 3, 4, 5} print(s.add(666)) print(s) print(s.add((1, 2, 3, 4))) print(s) # None # {1, 2, 3, 4, 5, 666} # None # {1, 2, 3, 4, 5, (1, 2, 3, 4), 666} # 集合是無序的
獲取集合元素個數 len
# len 長度 s = {1, 2, 3, 4, 5} print(len(s)) # 5
集合在交集並集關系處理中的運用 & | ^ - < <= > >= == 以及他們的英語方法寫法(后續補充一下)
# 交集並集等集合關系的運用 pythons = ['jason', 'nick', 'tank', 'egon', 'kevin', 'owen', 'alex'] linux = ['frank', 'jerry', 'tank', 'egon', 'alex'] # 求既在python 又在linux 的同學 # 普通循環寫法 for name in pythons: if name in linux: print(name) # tank # egon # alex pythons = {'jason', 'nick', 'tank', 'egon', 'kevin', 'owen', 'alex'} linux = {'frank', 'jerry', 'tank', 'egon', 'alex'} # & 交集 # pythons 和 linux中都有的 print(pythons & linux) # {'tank', 'alex', 'egon'} # - 差集 ----------------- # 只在 pythons 中的 print(pythons - linux) # {'kevin', 'nick', 'jason', 'owen'} # 只在 linux 中的 print(linux - pythons) # {'frank', 'jerry'} # ^ 對稱差集 # 沒有同時在 pythons 和 linux 中的 print(pythons ^ linux) # {'kevin', 'nick', 'jerry', 'owen', 'jason', 'frank'} # | 合集 # pythons 和 linux 所有的元素(不重復) print(pythons | linux) # {'kevin', 'frank', 'alex', 'egon', 'jason', 'tank', 'jerry', 'nick', 'owen'} # == 判斷兩個集合是否相等 print(pythons == linux) # False # 父級子級 s = {1, 2, 3, 4} s2 = {2, 4} # > >= 是否包含 (父級) issuperset print(s >= s2) # True # < <= 是否被包含 (子級) issubset # 父級自己反過來一樣的
刪除集合中的元素 pop remove clear discard 通用del
# pop 會返回刪除元素的值(集合是無序的---雖然看起來存進去的元素都是從小到大排序,但它不能索引取值,沒有參數) my_set = {2, 15, 13, 1} print(my_set.pop()) print(my_set.pop()) print(my_set) # 1 # 2 # {13, 15} # remove 刪除指定元素,沒有返回值,指定元素若不存在會報錯 my_set = {2, 15, 13, 1} print(my_set.remove(13)) print(my_set) # None # {1, 2, 15} # print(my_set.remove(22)) # 元素不存在,直接報錯 # discard 刪除指定元素,沒有返回值,指定元素不存在不報錯 my_set = {2, 15, 13, 1} print(my_set.discard(13)) print(my_set) print(my_set.discard(22)) print(my_set) # None # {1, 2, 15} # None # {1, 2, 15} # clear my_set = {2, 15, 13, 1} print(my_set) print(my_set.clear()) print(my_set) # {1, 2, 13, 15} # None # set() # del 通用刪除大法 my_set = {2, 15, 13, 1} del my_set # print(my_set) # 直接報錯,引用被刪除了
補充知識點
enumerate() : # enumerate枚舉:給可迭代對象(列表、字典)等類型添加序號
good_list = [ ['mac', 555], ['apple', 333] ] for index, good in enumerate(good_list): print(index, good) # 0 ['mac', 555] # 1 ['apple', 333]
區分類型
# 必須分清楚下面這幾種類型分別長啥樣!!!別寫混了 # 列表 list # [1, 2, 3, 4] # 元組 tuple # (1, 2, 3, 4) # 集合 set # {1, 2, 3, 4}
個人擴展案例及練習
# 處理省份之間突然有格式不對的東西(本來 、 隔開的,后來有些地方用 , , 隔開) # 目標數據格式:{'市名': ['各個市'], '市名': ['各個市']} # 南充市:順慶區、高坪區、嘉陵區、閬中市、南部縣、營山縣、蓬安縣、儀隴縣、西充縣 # 宜賓市:翠屏區、宜賓縣,南溪縣、江安縣、長寧縣、高縣、珙縣、筠連縣、興文縣、屏山縣 # 廣安市:廣安區、華鎣市、岳池縣、武勝縣,鄰水縣

region_info = '''南充市:順慶區、高坪區、嘉陵區、閬中市、南部縣、營山縣、蓬安縣、儀隴縣、西充縣 宜賓市:翠屏區、宜賓縣,南溪縣、江安縣、長寧縣、高縣、珙縣、筠連縣、興文縣、屏山縣 廣安市:廣安區,華鎣市,岳池縣、武勝縣,鄰水縣''' print(region_info) raw_infos = region_info.split('\n') print(raw_infos) dic = {} for raw_info in raw_infos: key, value = raw_info.split(':') dic[key] = value print(dic) for key, value in dic.items(): r_value = value.replace(',', '、') target_value = r_value.replace(',', '、') print(target_value) item = target_value.split('、') dic[key] = item # 南充市:順慶區、高坪區、嘉陵區、閬中市、南部縣、營山縣、蓬安縣、儀隴縣、西充縣 # 宜賓市:翠屏區、宜賓縣,南溪縣、江安縣、長寧縣、高縣、珙縣、筠連縣、興文縣、屏山縣 # 廣安市:廣安區,華鎣市,岳池縣、武勝縣,鄰水縣 # ['南充市:順慶區、高坪區、嘉陵區、閬中市、南部縣、營山縣、蓬安縣、儀隴縣、西充縣', '宜賓市:翠屏區、宜賓縣,南溪縣、江安縣、長寧縣、高縣、珙縣、筠連縣、興文縣、屏山縣', '廣安市:廣安區,華鎣市,岳池縣、武勝縣,鄰水縣'] # {'南充市': '順慶區、高坪區、嘉陵區、閬中市、南部縣、營山縣、蓬安縣、儀隴縣、西充縣', '宜賓市': '翠屏區、宜賓縣,南溪縣、江安縣、長寧縣、高縣、珙縣、筠連縣、興文縣、屏山縣', '廣安市': '廣安區,華鎣市,岳池縣、武勝縣,鄰水縣'} # 順慶區、高坪區、嘉陵區、閬中市、南部縣、營山縣、蓬安縣、儀隴縣、西充縣 # 翠屏區、宜賓縣、南溪縣、江安縣、長寧縣、高縣、珙縣、筠連縣、興文縣、屏山縣 # 廣安區、華鎣市、岳池縣、武勝縣、鄰水縣 print(dic) # {'南充市': ['順慶區', '高坪區', '嘉陵區', '閬中市', '南部縣', '營山縣', '蓬安縣', '儀隴縣', '西充縣'], '宜賓市': ['翠屏區', '宜賓縣', '南溪縣', '江安縣', '長寧縣', '高縣', '珙縣', '筠連縣', '興文縣', '屏山縣'], '廣安市': ['廣安區', '華鎣市', '岳池縣', '武勝縣', '鄰水縣']}
''' 1.有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中 即: {'k1': 大於66的所有值, 'k2': 小於66的所有值} 小提示:按照題意這里的k1和k2對應的value必須能存多個值 '''

s = {11, 22, 33, 44, 55, 66, 77, 88, 99, 90} d = {'k1': [], 'k2': []} for value in s: if value >= 66: d['k1'].append(value) else: d['k2'].append(value) print(d) # {'k1': [66, 99, 77, 88, 90], 'k2': [33, 11, 44, 22, 55]}
# 2.簡單購物車,要求如下: # 實現打印商品詳細信息,用戶輸入商品名和購買個數,則將商品名,價格,購買個數加入購物列表,如果輸入為空或其他非法輸入則要求用戶重新輸入 # msg_dic={ # 'apple':10, # 'tesla':100000, # 'mac':3000, # 'lenovo':30000, # 'chicken':10, # } # 小提示:打印的時候即需要拿到字典的key也需要拿到對應的value

# 邏輯還是有點混亂(Q/ y 輸錯了直接就重新購買商品了。。。) msg_dic = { 'apple': 10, 'tesla': 100000, 'mac': 3000, 'lenovo': 30000, 'chicken': 10, } shop_name = "" shop_count = "" choice = "" shop_car = [] total_price = 0 while True: print("歡迎光臨 online 商城".center(40, '-')) print("本店商品信息如下,歡迎搶購".center(35, '-')) for key, value in msg_dic.items(): print(f"商品:{key}, 單價:{value} ".ljust(40, '-')) print(''.center(46, '-')) shop_name = "" shop_count = "" shop_name = input("請輸入您要購買的商品>>>:") # 判斷商品是否存在 if shop_name.strip().lower() not in msg_dic: # 輸入有誤要求重新輸入 print("您輸入商品不存在或輸入非法,請重新輸入") # 輸入的商品在商品列表中 else: # 在購物車就更新數量,不在就加入 shop_count = input("請輸入您要購買商品數量>>>:") if not shop_count.strip().isdigit(): # 暫時是重新輸入商品 + 數量, 應該是只需要重新輸入數量就行了 print("您的輸入有誤,請重新輸入!") continue # 上面的if 已經確定 輸入的是數字了,現在給他轉成數字方便運算 shop_count = int(shop_count) # 輸入完畢將商品加入購物車(商品名、價格和個數) is_in_car = False # 判斷這個商品在不在購物車里 for shop_info in shop_car: # 在,那就給他更新個數 if shop_info.get('shop_name') == shop_name: shop_info['shop_count'] += shop_count # print(shop_info.setdefault(shop_price, msg_dic.get(shop_name))) is_in_car = True # 不是購物車里的商品,那就添加到購物車 if not is_in_car: # print(shop_car) # 新增一個字典,給它的值設 # new_shop = dict() new_shop = dict(shop_name=shop_name, shop_count=shop_count, shop_price=msg_dic.get(shop_name)) # new_shop['shop_name'] = shop_name # new_shop['shop_count'] = shop_count # new_shop['shop_price'] = msg_dic.get(shop_name) # print(new_shop) # 可以打印出來,添加商品成功 shop_car.append(new_shop) # 同樣的商品應該是數量累加 choice = input("商品已加入購物車,輸入Q / E 查看購物車(退出程序), 輸入C / Y 繼續購買>>>:").strip().lower() if choice in ['q', 'quit', 'e', 'exit']: # 輸出購買信息 print('您的購物車信息如下:') # 循環輸出購物車每個商品 print("購物車清單".center(40, '-')) for single_shop_info in shop_car: from_car_shop_name = single_shop_info.get('shop_name') from_car_shop_count = single_shop_info.get('shop_count') from_car_shop_price = single_shop_info.get('shop_price') # print(type(total_price), type(from_car_shop_count), type(from_car_shop_price)) total_price += int(from_car_shop_count) * int(from_car_shop_price) print(f"商品:{from_car_shop_name},數量:{from_car_shop_count},單價為:{from_car_shop_price}".center(40, ' ')) print("清單結束".center(40, '-')) print(f'共: {total_price} 元'.ljust(40, ' ')) break elif choice in ['c', 'continue', 'y', 'yes']: print(f"您輸入的 {shop_name}: {shop_count} 已加入購物車~") # 已經加入購物車了
''' 3.統計s='hello alex alex say hello sb sb'中每個單詞的個數 結果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2} '''

s = 'hello alex alex say hello sb sb' s_list = s.split(' ') s_dict = {} for word in s_list: if word in s_dict.keys(): s_dict[word] += 1 else: s_dict[word] = 1 print(s_dict) # {'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
# 4.關系運算 # 有如下兩個集合,pythons是報名python課程的學員名字集合,linuxs是報名linux課程的學員名字集合 # pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'} # linuxs={'wupeiqi','oldboy','gangdan'} # 1. 求出即報名python又報名linux課程的學員名字集合 # 2. 求出所有報名的學生名字集合 # 3. 求出只報名python課程的學員名字 # 4. 求出沒有同時這兩門課程的學員名字集合

pythons = {'alex', 'egon', 'yuanhao', 'wupeiqi', 'gangdan', 'biubiu'} linuxs = {'wupeiqi', 'oldboy', 'gangdan'} # 1. 求出即報名python又報名linux課程的學員名字集合 print(pythons & linuxs) # {'wupeiqi', 'gangdan'} # 2. 求出所有報名的學生名字集合 print(pythons | linuxs) # 'egon', 'wupeiqi', 'yuanhao', 'biubiu', 'gangdan', 'alex', 'oldboy'} # 3. 求出只報名python課程的學員名字 print(pythons - linuxs) # {'alex', 'biubiu', 'yuanhao', 'egon'} # 4. 求出沒有同時這兩門課程的學員名字集合 print(pythons ^ linuxs) # {'biubiu', 'oldboy', 'alex', 'yuanhao', 'egon'}
''' 5. 對列表l=['a','b',1,'a','a']內的元素完成去重得到新列表. 拔高:如果想去重並且想保持列表原來的順序該如何做? '''

# 1. 僅去重 l = ['a', 'b', 1, 'a', 'a'] l2 = list(set(l)) print(l2) # ['a', 1, 'b'] # 2.保持原來順序的去重 # 方式一,通過 .count 方法 l = ['a', 'b', 1, 'a', 'a'] l2 = [] for i in l: if l2.count(i) == 0: l2.append(i) print(l2) # ['a', 'b', 1] # 方式二,通過成員方法 in / not in l2 = [] for dic in l: if dic not in l2: l2.append(dic) print(l2)
# 6.對如下列表中的元素去重(),得到新列表,且新列表一定要保持列表原來的順序 # l=[ # {'name':'egon','age':18,'sex':'male'}, # {'name':'alex','age':73,'sex':'male'}, # {'name':'egon','age':20,'sex':'female'}, # {'name':'egon','age':18,'sex':'male'}, # {'name':'egon','age':18,'sex':'male'}, # ] # 小提示:去重不一定非要用集合

l = [ {'name': 'egon', 'age': 18, 'sex': 'male'}, {'name': 'alex', 'age': 73, 'sex': 'male'}, {'name': 'egon', 'age': 20, 'sex': 'female'}, {'name': 'egon', 'age': 18, 'sex': 'male'}, {'name': 'egon', 'age': 18, 'sex': 'male'}, ] l2 = [] for dic in l: if l2.count(dic) == 0: # if dic not in l2: # 方式二 l2.append(dic) print(l2) # [{'name': 'egon', 'age': 18, 'sex': 'male'}, {'name': 'alex', 'age': 73, 'sex': 'male'}, {'name': 'egon', 'age': 20, 'sex': 'female'}]