一、集合的基本定義和操作
Python的集合是一種無序的,不重複的數據類型,可以進行交集、聯合、差集等操作。集合在數據分析和清洗的過程中起到了至關重要的作用。
創建一個集合可以使用花括弧{}或set()函數。
{1, 2, 3, "a", "b", "c"}
set([1,2,3,"a","b","c"])
可以使用len()函數獲取集合的長度,使用in關鍵字判斷元素是否在集合中,使用add()函數添加元素。
s = {1,2,3,"a","b","c"}
len(s) # 返回6
"a" in s # 表達式的值為True
s.add("d") # 添加元素"d"
二、集合的操作
集合提供了一些常見的操作,包括聯合、交集、差集和對稱差集。
聯合操作:使用union()函數或者|運算符可以實現兩個集合的聯合,返回一個包含兩個集合中所有不重複元素的新集合。
s1 = {1,2,3,"a","b","c"}
s2 = {3,4,5,"c","d","e"}
s3 = s1.union(s2) # 返回 {1,2,3,4,5,"a","b","c","d","e"}
s4 = s1 | s2 # 返回 {1,2,3,4,5,"a","b","c","d","e"}
交集操作:使用intersection()函數或者&運算符可以實現兩個集合的交集,返回一個包含兩個集合中共同元素的新集合。
s1 = {1,2,3,"a","b","c"}
s2 = {3,4,5,"c","d","e"}
s3 = s1.intersection(s2) # 返回 {3,"c"}
s4 = s1 & s2 # 返回 {3,"c"}
差集操作:使用difference()函數或者-運算符可以實現兩個集合的差集,返回一個包含一個集合中不包含於另一個集合的元素的新集合。
s1 = {1,2,3,"a","b","c"}
s2 = {3,4,5,"c","d","e"}
s3 = s1.difference(s2) # 返回 {1,2,"a","b"}
s4 = s1 - s2 # 返回 {1,2,"a","b"}
對稱差集操作:使用symmetric_difference()函數或者^運算符可以實現兩個集合的對稱差集,返回一個包含兩個集合中不重複元素的新集合。
s1 = {1,2,3,"a","b","c"}
s2 = {3,4,5,"c","d","e"}
s3 = s1.symmetric_difference(s2) # 返回 {1,2,4,5,"a","b","d","e"}
s4 = s1 ^ s2 # 返回 {1,2,4,5,"a","b","d","e"}
三、集合的應用
1、去重應用
在數據清洗和整理過程中,經常需要去重操作以保證數據的準確性和完整性。使用集合可以快速實現列表、元組和字典等數據類型的去重。
l = [1,2,2,3,4,4,4,5]
l = list(set(l)) # 返回 [1,2,3,4,5]
t = (1,2,2,3,4,4,4,5)
t = tuple(set(t)) # 返回 (1,2,3,4,5)
d = {"a":1,"b":2,"c":2,"d":3,"e":3}
d = dict((y,x) for x,y in d.items())
d = dict((x,y) for y,x in d.items()) # 返回 {"a":1,"b":2,"d":3,"e":3}
2、成員資格測試應用
在數據分析和處理過程中,需要對數據進行篩選和分類,使用集合可以快速篩選數據是否符合要求。
words = ["apple","banana","orange","pineapple"]
"apple" in set(words) # 返回True
3、數據分析應用
集合在數據分析和統計中有廣泛的應用,例如實現一個統計文本中單詞出現次數的程序。
text = "Python is a popular programming language. Python is used for web development, data analysis, artificial intelligence, and scientific computing."
words = text.split(" ")
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 0
word_count[word] += 1
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
for word, count in sorted_word_count:
print(word, count)
運行結果為:
Python 2
is 2
a 1
popular 1
programming 1
language. 1
used 1
for 1
web 1
development, 1
data 1
analysis, 1
artificial 1
intelligence, 1
and 1
scientific 1
computing. 1
原創文章,作者:RXNX,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/144685.html