「python」set集合

 

在python3中按數據類型的可變與不可變大致分爲如下幾種類型,前面已經介紹了另外幾種了。今天講講set。

不可變數據(3 個):Number(數字)、String(字符串)、Tuple(元組);
可變數據(3 個):List(列表)、Dictionary(字典)、Set(集合)。

1.set是什麼?用來幹什麼?

python中,用set來表示一個無序不重複元素的序列。set的只要作用就是用來給數據去重。 

可以使用大括號 { } 或者 set() 函數創建集合,

但是注意如果創建一個空集合必須用 set() 而不是 { },因爲{}是用來表示空字典類型的

1.1.set的集合的創建與使用

#1.用{}創建set集合
person ={"student","teacher","babe",123,321,123} #同樣各種類型嵌套,可以賦值重複數據,但是存儲會去重
print(len(person))  #存放了6個數據,長度顯示是5,存儲是自動去重.
print(person) #但是顯示出來則是去重的
'''
5
{321, 'teacher', 'student', 'babe', 123}
'''
#2.空set集合用set()函數表示
person1 = set() #表示空set,不能用person1={}
print(len(person1))
print(person1)
'''
0
set()
'''

 

#3.用set()函數創建set集合
person2 = set(("hello","jerry",133,11,133,"jerru")) 
  #只能傳入一個參數,可以是list,tuple等 類型
print(len(person2))
print(person2)
'''
5
{133, 'jerry', 11, 'jerru', 'hello'}
'''

1.2.常見使用注意事項 

#1.set對字符串也會去重,因爲字符串屬於序列。

使用“-”表示求差;但是不可以使用“+”;


str1 = set("abcdefgabcdefghi")
str2 = set("abcdefgabcdefgh")
print(str1,str2)
print(str1 - str2) #-號可以求差集
print(str2-str1)  #空值
#print(str1+str2)  #set裏不能使用+號
====================================================================
{'d', 'i', 'e', 'f', 'a', 'g', 'b', 'h', 'c'} {'d', 'e', 'f', 'a', 'g', 'b', 'h', 'c'}
{'i'}
set()

2.set集合的增刪改查操作

2.1添加數據

add函數和update函數區別:

add:如果元素,比如字符串已經存在不會被拆分;但是update添加字符串時會被拆分

add:如元素已經存在,則不會保存,也不會進行什麼處理,等於沒用

update:可以添加元組,或者字典

add:不可以添加list,但是可以添加元組

#1.給set集合增加數據
person ={"student","teacher","babe",123,321,123}
person.add("student") #如果元素已經存在,則不報錯,也不會添加,不會將字符串拆分成多個元素,去別update
print(person)
person.add((1,23,"hello")) #可以添加元組,但不能是list
print(person)
'''
{321, 'babe', 'teacher', 'student', 123}
{(1, 23, 'hello'), 321, 'babe', 'teacher', 'student', 123}
'''
 
person.update((1,3)) #可以使用update添加一些元組列表,字典等。但不能是字符串,否則會拆分
print(person)
person.update("abc")
print(person)  #會將字符串拆分成a,b,c三個元素
'''
{321, 1, 3, 'teacher', (1, 23, 'hello'), 'babe', 'student', 123}
{321, 1, 3, 'b', 'c', 'teacher', (1, 23, 'hello'), 'a', 'babe', 'student', 123}
'''
 

2.2 刪除數據

remove:根據元素內容刪除元素,如果元素不存在會報錯

discard:和remove功能一樣,但是不會存在報錯

pop:在list中刪除最後一個,在set中刪除隨機的一個

#2.從set裏刪除數據
person.remove("student")#按元素去刪除
print(person)
#print("student")如果不存在 ,會報錯。
'''
{321, 1, 3, 'c', 'b', (1, 23, 'hello'), 'teacher', 'babe', 'a', 123}
'''
person.discard("student")#功能和remove一樣,好處是沒有的話,不會報錯
person.pop() #在list裏默認刪除最後一個,在set裏隨機刪除一個。
print(person)
'''
{1, 3, (1, 23, 'hello'), 'teacher', 'b', 'a', 'babe', 123, 'c'}
'''

2.3 更新

因爲是無序的,沒有角標。所以更新只能使用remove+add

#3.更新set中某個元素,因爲是無序的,所以不能用角標
#所以一般更新都是使用remove,然後在add
 

2.4 查詢

使用in判斷是否存在

#4.查詢是否存在,無法返回索引,使用in判斷
if "teacher" in person:
    print("true")
else:
    print("不存在")
'''
true
'''

2.5 清空

#5.終極大招:直接清空set
print(person)
person.clear()
print(person)
'''
set()
'''

轉載:https://blog.csdn.net/qq_26442553/article/details/81809116

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章