首頁 > 軟體

Python中集合的建立及常用函數的使用詳解

2022-06-23 14:01:00

集合的建立

使用內建函數set()進行轉化或者使用{}包括起來的,集合中的元素:無序性,互異性,確定性。

舉例:

numbers=set(range(0,7))//使用內建函數進行轉化
print(numbers)
print(type(numbers))

輸出:

{0, 1, 2, 3, 4, 5, 6}
<class 'set'>

互異性

fruit={'apple','orange','banana',"apple",'apple','orange','banana',"apple"}
print(fruit)
print(type(fruit))

輸出:

{'apple', 'banana', 'orange'}
<class 'set'>

無序性

集合中的元素不能通過下標存取。

舉例:

fruit =set({'apple',9,"axn","dbu",12})
print(fruit[2])

集合中的操作函數

在集合中新增元素

add() 函數

舉例:

fruit =set({'apple',9,"axn","dbu",12})
fruit.add("bc")
print(fruit)

輸出:

{'bc', 'apple', 9, 12, 'dbu', 'axn'}

刪除集合中的第一個元素

pop()函數

舉例:

fruit =set({'apple',9,"axn","dbu",12})
fruit.pop()
print(fruit)

輸出:

{'apple', 9, 12, 'axn'}

刪除集合中的指定元素

1:remove()函數,若該元素不存在則會報錯

舉例:

fruit =set({'apple',9,"axn","dbu",12})
fruit.remove("banana")
print(fruit)

fruit =set({'apple',9,"axn","dbu",12,"apple"})
fruit.remove("apple")
print(fruit)

輸出:

{'dbu', 'axn', 9, 12}

2:discard()函數,若指定元素不存在不會報錯

舉例:

fruit =set({'apple',9,"axn","dbu",12,"apple"})
fruit.discard("banana")
print(fruit)

輸出:

{'dbu', 'apple', 9, 'axn', 12}

fruit =set({'apple',9,"axn","dbu",12,"apple"})
fruit.discard("apple")
print(fruit)

輸出:

{'dbu', 'axn', 9, 12}

判斷元素是否在集合裡面

if in/not in語句

舉例:

fruit =set({'apple',9,"axn","dbu",12,"apple"})
if "apple" in fruit:
    print("yes")
else:
    print("NO")
if "banana" not in fruit:
    print("YES")
else:
    print("NO")

輸出:

yes
YES

集合的遍歷

for迴圈

fruit =set({'apple',9,"axn","dbu",12,"apple"})
for i in fruit:
    print(i,end=' ')

輸出:

axn 9 apple 12 dbu 

集合元素個數的計算

len()函數

舉例:

fruit =set({'apple',9,"axn","dbu",12,"apple"})
print(len(fruit))

輸出:

5//注意集合元素的唯一性特徵

集合與字典,列表,元組的巢狀

集合與字典:

s1=set({"name":"jason","age":19,"地址":"北京市"})
print(s1)
print(type(s1))

輸出:

{'地址', 'name', 'age'}//只輸出鍵名
<class 'set'>

集合與元組

舉例:

s1={("name","jason","age",19,"地址","北京市"),12,34,0}
print(s1)
print(type(s1))

輸出:

{0, 34, ('name', 'jason', 'age', 19, '地址', '北京市'), 12}
<class 'set'>

使用內建函數進行轉化:

s1=set({"name","jason","age",19,"地址","北京市"})
print(s1)
print(type(s1))

輸出:

{'age', 'jason', 19, '地址', '北京市', 'name'}
<class 'set'>

集合與列表

舉例:

s2=set(["name","jason","age",19,"地址","北京市"])
print(s2)
print(type(s2))

輸出:

{'北京市', 'age', 'jason', 19, 'name', '地址'}
<class 'set'>

到此這篇關於Python中集合的建立及常用函數的使用詳解的文章就介紹到這了,更多相關Python集合內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com