python之集合与字典
01 一山不容二虎的集合
1.通俗來說,集合(set)是一個無序的不重復元素序列,就是一個用來存放數據的容器。
1)集合里面的元素是不可重復的:
如:
s = {1,2,3,4,1,2,3} print(s,type(s)) # 輸出結果 {1, 2, 3, 4} <class 'set'>2)如何定義一個空集合:
s1 = {} #這種定義的是空字典 print(s1,type(s1)) {} <class 'dict'>s2 = set([]) #定義一個空集合 print(s2,type(s2)) set() <class 'set'>s3 = set() #也是定義空集合 print(s3,type(s3)) set() <class 'set'>2.集合的創建:?使用大括號 { } 或者 set() 函數創建集合;
3.?注意:
- 創建一個空集合必須用 set() 而不是 { }.{ } 是用來創建一個空字典
輸出結果:
{} <class 'dict'>
set() <class 'set'>
set() <class 'set'>
- 集合里面的元素必須是不可變的數據類型;(列表是可變數據類型)?
- 通過set方法可以將列表/元組/字符串轉換成集合數據類型。
3.集合的特性:
集合是一個無序的數據類型。最后增加的元素不一定存儲在集合最后。
可以從索引, 切片, 重復, 連接, 成員操作符和for循環來看其特性
集合支持的特性只有成員操作符,索引,切片,重復,連接,均不支持!
s = {1,3,5,7} print(1 in s) True print(1 not in s) False?4,集合的內置方法:
1)增加:集合是可變, 無序數據類型,添加的順序, 和在集合中存儲的順序不同
(add:增加一個,update:增加多個)
s = {2,3,4,3,5} s.add(1) #增加一個 print(s) {1, 2, 3, 4, 5} s.update({7,8,9}) #增加多個 print(s) {1, 2, 3, 4, 5, 7, 8, 9}2)刪除:
1>pop(隨機彈出并返回刪除的值)
s = {6,7,3,1,2,4} print(s) {1, 2, 3, 4, 6, 7} s.pop() Out[41]: 1 print(s) {2, 3, 4, 6, 7}?2>.remove(如果元素存在, 直接刪除, 如果不存在, 拋出異常KeyError)
s = {6,7,3,1,2,3} print(s) {1, 2, 3, 6, 7} s.remove(6) #刪除指定的元素 print(s) {1, 2, 3, 7}3>discard:(如果元素存在, 直接刪除, 如果不存在, do nothing)只能刪除單個元素。
s1 = {1,2,3,4,5} s1.discard(3,4) #.discard一次只能刪除一個元素 Traceback (most recent call last):File "E:\software-python\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2961, in run_codeexec(code_obj, self.user_global_ns, self.user_ns)File "<ipython-input-3-44fe7abbc30b>", line 1, in <module>s1.discard(3,4) TypeError: discard() takes exactly one argument (2 given) s1 = {1,2,3,4,5} s1.discard(3) print(s1) {1, 2, 4, 5}5.集合應用案例:(列表去重)
案例1: URL地址去重:
>方法1:列表遍歷,用.append()追加
urls = ['http://www.baidu.com','http://www.qq.com','http://www.qq.com','http://www.163.com','http://www.csdn.com','http://www.csdn.com', ]# 用來存儲去重的url地址 analyze_urls = []# 依次遍歷所有的url for url in urls:# 如果url不是analyze_urls列表成員, 則追加到列表最后。# 如果url是analyze_urls列表成員,不做任何操作。if url not in analyze_urls:analyze_urls.append(url) print("去重之后的url地址: ", analyze_urls)>方法2:集合的性質去重:
?代碼如下:(此處的urls定義為集合urls{}同樣可以完成,效果一致)
urls = ['http://www.baidu.com','http://www.qq.com','http://www.qq.com','http://www.163.com','http://www.csdn.com','http://www.csdn.com', ]print("去重之后的url地址: ",set(urls)) #設置輸出的格式為集合類型案例2: 判斷列表去重前后元素長度是否一致:即是否存在重復元素的判斷
nums = [1,2,3,4,2,3] #如果此處nums是用集合{}定義的,結果永遠都是false # 存在重復元素: 判斷nums的長度和去重之后的長度是否一致, # 如果不一致, 則有重復的元素, 返回True # 如果一致, 則沒有重復的元素, 返回False print(len(nums) != len(set(nums))) # 結果為truenums = [1, 2, 3, 4] # 存在重復元素: 判斷nums的長度和去重之后的長度是否一致, # 如果不一致, 則有重復的元素, 返回True # 如果一致, 則沒有重復的元素, 返回False print(len(nums) != len(set(nums))) #結果為False案例3:華為筆試編程題: 明明的隨機數(去重與排序)
題目:明明想在學校中請一些同學一起做一項問卷調查,為了實驗的客觀性,他先用計算機生成了N個1到1000之間的 隨機整數(N≤1000),對于其中重復的數字,只保留一個,把其余相同的數去掉,不同的數對應著不同的學 生的學號。然后再把這些數從大到小排序,按照排好的順序去找同學做調查。請你協助明明完成“去重”與?“排序”的工作(同一個測試用例里可能會有多組數據,希望大家能正確處理)。
思路:
- 1). 生成了N個1到1000之間的隨機整數(N≤1000)
- 2). 去重: 其中重復的數字,只保留一個,把其余相同的數去掉
- 3). 從大到小排序
案例4:兩個數組的交集:
示例 1:
輸入: nums1 = [1,2,2,1], nums2 = [2,2]
輸出: [2]
示例 2:
輸入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出: [9,4]
說明:輸出結果中的每個元素一定是唯一的。
我們可以不考慮輸出結果的順序。
02?frozenset
- frozenset?是?set?的不可變版本,因此?set?集合中所有能改變集合本身的方法(如?add、 remove、discard、xxx_update?等),frozenset都不支持;
- set?集合中不改變集合本身的方法,fronzenset?都支持。
- frozenset?的這些方法和?set?集合同名方法的功能完全相同。
frozenset?的作用主要有兩點:
?
- 當集合元素不需要改變時,使用?frozenset?代替?set?更安全。
- 當某些?API?需要不可變對象時,必須用?frozenset?代替set。比如?dict?的?key?必須 是不可變對象,因此只能用 frozenset;
- 再比如?set?本身的集合元素必須是不可變 的,因此 set?不能包含?set,set?只能包含?frozenset。?
如:
set1 = frozenset({1,2,3,4}) print(set1,type(set1)) frozenset({1, 2, 3, 4}) <class 'frozenset'> set2 = {1,2,set1} print(set2) {1, 2, frozenset({1, 2, 3, 4})}03?字典
字典是另一種可變容器模型,且可存儲任意類型對象。?鍵一般是唯一的,如果重復最后的一個鍵值對會替換前面的,值不需要唯一。
d ={key1 : value1, key2 : value2 } d = {'Z' : '字', 'D' : '典' }
1). 字典可以快速通過key值查詢到value值。O(1) ;
2). key值是不能重復的, value值無所謂 ;
3). 字典的key值必須是不可變的數據類型, value值可以是任意數據類型。
1.字典的創建于刪除
1). 簡單字典創建
dict = {"name": "fentiao", "age": 4, "gender": "male"} print(dict['name']) print(dict["age"])# 輸出結果 # fentiao # 42)空字典的定義:
s = {} print(type(s)) d = dict() print(d) print(type(d)) print(type(dict()))# 輸出結果 # <class 'dict'> # {} # <class 'dict'> # <class 'dict'>2). 內建方法:fromkeys
? ? ? ? ? ?字典中的key有相同的value值,如果沒有進行設定,默認相同的value值為None
ddict = {}.fromkeys(('username', 'password'), 'wlh') print(ddict) ddict = {}.fromkeys(('username', 'password')) print(ddict) # 輸出結果 # {'username': 'wlh', 'password': 'wlh'} # {'username': None, 'password': None}3). zip間接創建(對應關系)
userInfo = zip(["name", 'age'], ["wlh", 12]) print(userInfo) print(dict(userInfo)) # 輸出結果 # <zip object at 0x0000000002949EC8> # {'name': 'wlh', 'age': 12}2.字典內建方法
1>字典的查看
students = {'user1': [100, 100, 100],'user2': [98, 100, 100],'user3': [100, 89, 100], }# 字典的查看 # 通過字典的key獲取對應的value值; print(students['user1']) # print(students['user4']) # KeyError: 'user4', 因為key值在字典中不存在# 特別重要: get方法: 如果key存在獲取對應的value值, 反之, 返回默認值(如果不指定,默認返回的是None) print(students.get('user1')) # [100, 100, 100] print(students.get('user4', 'no user')) # 'no user' print(students.get('user1', 'user2')) # [100, 100, 100]# 查看所有的key值/value值/key-value值 print(students.keys()) print(students.values()) print(students.items()) # key-value值 [(key1, value1),(key2, value2)]運行結果: [100, 100, 100] [100, 100, 100] no user dict_keys(['user1', 'user2', 'user3']) dict_values([[100, 100, 100], [98, 100, 100], [100, 89, 100]]) dict_items([('user1', [100, 100, 100]), ('user2', [98, 100, 100]), ('user3', [100, 89, 100])])2>.循環遍歷字典:
# for循環字符串 # for item in 'abc': # print(item)# for循環元組 # for item in (1, 2, 3): # print(item) # # for循環集合 # for item in {1, 2, 3}: # print(item)students = {'user1': [100, 100, 100],'user2': [98, 100, 100],'user3': [100, 89, 100], }# 字典遍歷時默認遍歷的時字典的key值 for key in students:print(key, students[key])# 遍歷字典key-value建議的方法 for key,value in students.items(): # [('user1', [100, 100, 100]), ('user2', [98, 100, 100]), ('user3', [100, 89, 100])]# key,value = ('user1', [100, 100, 100])# key,value = ('user2', [98, 100, 100])# key,value = ('user3', [100, 89, 100])print(key, value)運行結果: user1 [100, 100, 100] user2 [98, 100, 100] user3 [100, 89, 100] user1 [100, 100, 100] user2 [98, 100, 100] user3 [100, 89, 100]3>字典的增加方法
1). 根據key增加 /修改key-value
- 如果key存在, 修改key-value
- 如果key不存在, 增加key-value
2)setdefault方法
如果key存在, 不做任何操作
如果key不存在, 增加key-value
?2)update方法
批量添加key-value
如果key存在, 修改key-value
如果key不存在, 增加key-value
4>字典的刪除
1). del dict[key]
?# 如果key存在, 刪除對應的value值
?# 如果key不存在, 拋出異常KeyError
students = {'user1': [100, 100, 100],'user2': [98, 100, 100],'user3': [100, 89, 100], }del students['user1'] print(students)結果: {'user2': [98, 100, 100], 'user3': [100, 89, 100]}2)pop方法
1.#如果key存在, 刪除對應的value值
2.#如果key不存在,如果沒有提供默認值, 則拋出異常KeyError
students = {'user1': [100, 100, 100],'user2': [98, 100, 100],'user3': [100, 89, 100], }delete_item = students.pop('user6', 'no user') print("刪除的元素是: ", delete_item) print(students)結果是: 刪除的元素是: no user {'user1': [100, 100, 100], 'user2': [98, 100, 100], 'user3': [100, 89, 100]}3). popitem方法: 隨機刪除字典的key-value值
students = {'user1': [100, 100, 100],'user2': [98, 100, 100],'user3': [100, 89, 100], }key, value = students.popitem() print("隨機刪除的內容: ", key, value) 結果: 隨機刪除的內容: user3 [100, 89, 100]3.英文文本預處理:英文詞頻統計器
作為字典(key-value)的經典應用題目,單詞統計幾乎出現在每一種語言鍵值對學習后的必練題目。
主要需求: 寫一個函數wordcount統計一篇文章的每個單詞出現的次數(詞頻統計)。
統計完成后,對該統計按單詞頻次進行排序。
from collections import Counter text = """ Introducing Red Hat Enterprise Linux 7 Red Hat Enterprise Linux 7 showcases the latest features in an enterprise operating system Introducing Red Hat Enterprise Linux 7 Red Hat Enterprise Linux 7 showcases the latest features in an enterprise operating system Introducing Red Hat Enterprise Linux 7 Red Hat Enterprise Linux 7 showcases the latest features in an enterprise operating system Introducing Red Hat Enterprise Linux 7 Red Hat Enterprise Linux 7 showcases the latest features in an enterprise operating systemEnterprise architects will appreciate new capabilities such as lightweight application isolation.Application developers will welcome an updated development environment and application-profiling tools. Read more at the Red Hat Developer Blog.System administrators will appreciate new management tools and expanded file-system options with improved performance and scalability.Deployed on physical hardware, virtual machines, or in the cloud, Red Hat Enterprise Linux 7 delivers the advanced features required for next-generation architectures.Where to go from here:Red Hat Enterprise Linux 7 Product PageThe landing page for Red Hat Enterprise Linux 7 information. Learn how to plan, deploy, maintain, and troubleshoot your Red Hat Enterprise Linux 7 system.Red Hat Customer PortalYour central access point to finding articles, videos, and other Red Hat content, as well as manage your Red Hat support cases.DocumentationProvides documentation related to Red Hat Enterprise Linux and other Red Hat offerings.Red Hat Subscription ManagementWeb-based administration interface to efficiently manage systems.Red Hat Enterprise Linux Product PageProvides an entry point to Red Hat Enterprise Linux product offerings. """ # 1. 先拿出字符串里面的所有單詞; words = text.split() # ['hello', 'world', 'hello', 'python', 'hello', 'java'] """ text = "hello world hello python hello java" words = ['hello', 'world', 'hello', 'python', 'hello', 'java'] word_count_dict = {'hello': 3, 'world': 1, 'python':1, 'java':1 }""" # 2. 統計每個單詞出現的次數 # 1). 如何存儲統計好的信息: 字典存儲{'hello':3, 'world':1, 'python':1, 'java':1} # 2). 如何處理? word_count_dict = {} for word in words:if word not in word_count_dict:word_count_dict[word] = 1else:word_count_dict[word] += 1 print(word_count_dict) # 3. 排序,獲取出現次數最多的單詞 counter = Counter(word_count_dict) print(counter.most_common(5))結果:
{'Introducing': 4, 'Red': 21, 'Hat': 21, 'Enterprise': 16, 'Linux': 15, '7': 12, 'showcases': 4, 'the': 7, 'latest': 4, 'features': 5, 'in': 5, 'an': 6, 'enterprise': 4, 'operating': 4, 'system': 4, 'architects': 1, 'will': 3, 'appreciate': 2, 'new': 2, 'capabilities': 1, 'such': 1, 'as': 3, 'lightweight': 1, 'application': 1, 'isolation.': 1, 'Application': 1, 'developers': 1, 'welcome': 1, 'updated': 1, 'development': 1, 'environment': 1, 'and': 6, 'application-profiling': 1, 'tools.': 1, 'Read': 1, 'more': 1, 'at': 1, 'Developer': 1, 'Blog.': 1, 'System': 1, 'administrators': 1, 'management': 1, 'tools': 1, 'expanded': 1, 'file-system': 1, 'options': 1, 'with': 1, 'improved': 1, 'performance': 1, 'scalability.': 1, 'Deployed': 1, 'on': 1, 'physical': 1, 'hardware,': 1, 'virtual': 1, 'machines,': 1, 'or': 1, 'cloud,': 1, 'delivers': 1, 'advanced': 1, 'required': 1, 'for': 2, 'next-generation': 1, 'architectures.': 1, 'Where': 1, 'to': 6, 'go': 1, 'from': 1, 'here:': 1, 'Product': 2, 'Page': 2, 'The': 1, 'landing': 1, 'page': 1, 'information.': 1, 'Learn': 1, 'how': 1, 'plan,': 1, 'deploy,': 1, 'maintain,': 1, 'troubleshoot': 1, 'your': 2, 'system.': 1, 'Customer': 1, 'Portal': 1, 'Your': 1, 'central': 1, 'access': 1, 'point': 2, 'finding': 1, 'articles,': 1, 'videos,': 1, 'other': 2, 'content,': 1, 'well': 1, 'manage': 2, 'support': 1, 'cases.': 1, 'Documentation': 1, 'Provides': 2, 'documentation': 1, 'related': 1, 'offerings.': 2, 'Subscription': 1, 'Management': 1, 'Web-based': 1, 'administration': 1, 'interface': 1, 'efficiently': 1, 'systems.': 1, 'entry': 1, 'product': 1} [('Red', 21), ('Hat', 21), ('Enterprise', 16), ('Linux', 15), ('7', 12)]Process finished with exit code 04.列表去重
li = [1,2,3,4,65,1,2,3] print({}.fromkeys(li).keys())結果為: dict_keys([1, 2, 3, 4, 65])5.switch語句實現
注意:?python中沒有switch語句, 如何間接實現?
python里面不支持switch語句;
C/C++/Java/Javascript:switch語句是用來簡化if語句的.
1)老方法:
grade = input('Grade: ') if grade =='A':print("優秀") elif grade == 'B':print("良好") elif grade == 'C':print("合格") else:print('無效的成績')運行結果: Grade: D 無效的成績Grade: A 優秀2)新方法(更加的簡化)
grade = input('Grade: ') grades_dict = {'A': '優秀','B': '良好','C': '及格','D': '不及格', } print(grades_dict.get(grade, "無效的等級")) # if grade in grades_dict: # print(grades_dict[grade]) # else: # print("無效的等級")運行結果: Grade: B 良好Grade: C 及格04?defaultdict(默認字典)
1.當我使用普通的字典時,用法一般是dict={},添加元素的只需要dict[element] =value即,調用的時候也是如此,dict[element] = xxx,但前提是element在字典里,如果不在字典里就會報錯,如:
2.這時defaultdict就能排上用場了,defaultdict的作用是在于,當字典里的key不存在但被查找時,返回的不是keyError而是一個默認值。
- collections.defaultdict類,本身提供了默認值的功能,?默認值可以是整形,列表,集合等.
- defaultdict 是 dict 的子類。但它與 dict 最大的區別在于,如果程序試圖根據不存在的 key 訪問 value,會引發 KeyError 異常;
- 而 defaultdict 提供default_factory 屬性,為該不存在的 key 來自動生成生成默認的 value。
需求:
我們想要一個能將鍵(key)映射到多個值的字(即所謂的一鍵多值字典)
解決方案:
1). 字典是一種關聯容器,每個鍵都映射到一個單獨的值上。如果想讓鍵映射到多個值,
需要將這些多個 值保存到容器(列表或者集合)中。
2). 利用collections模塊中的defaultdict類自動初始化第一個值,這樣只需關注添加元素。
from collections import defaultdictinfo = defaultdict(int) info['a'] += 1 print(info['a'])運行結果: 1 from collections import defaultdictinfo = defaultdict(list) info['a'].append(1) print(info['a'])結果為: [1]3.?案例練習:
用defaultdict來做一個練習,把list(隨機生成50個1-100之間的隨機數)中大于66的元素和小于66的元素分辨出來
{
'大于66的元素': [71,8 2, ,83],
'小于66的元素': [1, 2, 3],
}
from collections import defaultdict# 1). 隨機生成50個1-100之間的隨機數 import random nums = [] for count in range(50):nums.append(random.randint(1, 100))# 2). 把list中大于66的元素和小于66的元素分類存儲 sort_nums_dict = defaultdict(list) # 創建一個默認字典, 默認的value為空列表[] for num in nums:if num > 66:sort_nums_dict['大于66的元素'].append(num)else:sort_nums_dict['小于66的元素'].append(num) print(sort_nums_dict)運行結果為: defaultdict(<class 'list'>, {'小于66的元素': [64, 39, 13, 1, 21, 9, 33, 27, 54, 8, 19, 36, 7, 7, 32, 54, 4, 20, 27, 17, 41, 6, 35, 60, 2, 21, 51, 23, 17, 49, 29, 7, 53, 56], '大于66的元素': [89, 70, 81, 91, 78, 98, 82, 87, 90, 100, 85, 71, 95, 80, 93, 82]})05?內置數據結構總結
1.可變與不可變數據類型
可變數據類型:可以增刪改。
- 可變數據類型允許變量的值發生變化,即如果對變量進行append、+=等這種操作后,只是改變了變量的值,而不會新建一個對象;
- 變量引用的對象的地址也不會變化,不過對 于相同的值的不同對象,在內存中則會存在不同的對象;
- 即每個對象都有自己的地址,相當于內存中對 于同值的對象保存了多份;
- 這里不存在引用計數,是實實在在的對象。
?不可變數據類型:不可以增刪改。
- python中的不可變數據類型,不允許變量的值發生變化;
- 如果改變了變量的值, 相當于是新建了一個對象;
- 而對于相同的值的對象,在內存中則只有一個對象,內部會有一個引用計數來記錄有多少個變量引用這個對象。
2.?有序序列和無序序列
有序序列擁有的特性:?索引、切片、連接操作符、重復操作符以及成員操作符等特性。
?所以:列表、字符串、元組是python的有序序列;
? ? ? ? ? ? 集合、字典是python的無序序列。
小練習1:
問題描述:
有一個列表,其中包括 10 個元素,例如這個列表是[1,2,3,4,5,6,7,8,9,0],要求將列表中的每個元素一次向前移動一個位置,第一個元素到列表的最后,然后輸出這個列表。最終樣式是[2,3,4,5,6,7,8,9,0,1]
a=input("請輸入一個列表:") alist=a.split(",") a1 = [int(alist[i]) for i in range(len(alist))] a2=a1.pop(0) a1.append(a2) print(a1)結果: 請輸入一個列表:1,2,3,4,5,6,7,8,9,0 [2, 3, 4, 5, 6, 7, 8, 9, 0, 1]?
總結
以上是生活随笔為你收集整理的python之集合与字典的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: loadRunner安装及使用步骤
- 下一篇: python lxml xpath_Py