python集合用法_Python 集合(Set)
集合
集合是無(wú)序、無(wú)索引的數(shù)據(jù)集。在Python中,集合用花括號(hào)包裹。
示例
創(chuàng)建集合:
thisset = {"自行車", "汽車", "高鐵"}
print(thisset)
注意: 集合是無(wú)序的,因此項(xiàng)目將以隨機(jī)順序出現(xiàn)。
訪問(wèn)集合項(xiàng)目
不能通過(guò)索引來(lái)訪問(wèn)集合項(xiàng),因?yàn)榧鲜菬o(wú)序的,這些項(xiàng)沒有索引。
但是您可以使用for循環(huán)遍歷集合項(xiàng),使用in關(guān)鍵字查詢集合中是否存在指定值。
示例
遍歷集合,并打印值:
thisset = {"自行車", "汽車", "高鐵"}
for x in thisset:
print(x)
示例
檢查“汽車”是否出現(xiàn)在集合中:
thisset = {"自行車", "汽車", "高鐵"}
print("汽車" in thisset)
修改項(xiàng)目
集合一旦創(chuàng)建,就不能更改,但是可以添加新項(xiàng)。
添加項(xiàng)目
要向集合中添加一項(xiàng),使用add()方法。
若要向集合添加多個(gè)項(xiàng),使用update()方法。
示例
使用add()方法向集合添加一個(gè)項(xiàng):
thisset = {"自行車", "汽車", "高鐵"}
thisset.add("飛機(jī)")
print(thisset)
示例
使用update()方法向一個(gè)集合添加多個(gè)項(xiàng):
thisset = {"自行車", "汽車", "高鐵"}
thisset.update(["飛機(jī)", "輪船", "電動(dòng)車"])
print(thisset)
獲取集合長(zhǎng)度
要確定一個(gè)集合有多少項(xiàng),可以使用len()方法。
示例
獲取集合長(zhǎng)度:
thisset = {"自行車", "汽車", "高鐵"}
print(len(thisset))
刪除項(xiàng)目
要?jiǎng)h除集合中的項(xiàng),使用remove()或discard()方法。
示例
使用remove()方法刪除“汽車”:
thisset = {"自行車", "汽車", "高鐵"}
thisset.remove("汽車")
print(thisset)
注意: 如果要?jiǎng)h除的項(xiàng)不存在,remove()將引發(fā)錯(cuò)誤。
示例
使用discard()方法刪除“汽車”:
thisset = {"自行車", "汽車", "高鐵"}
thisset.discard("汽車")
print(thisset)
注意: 如果要?jiǎng)h除的項(xiàng)不存在,discard()不會(huì)引發(fā)錯(cuò)誤。
您還可以使用pop()方法刪除項(xiàng),但該方法只刪除最后一項(xiàng)。因?yàn)榧鲜菬o(wú)序的,所以您不知道刪除了哪些項(xiàng)。
pop()方法的返回值是已刪除的項(xiàng)。
示例
使用pop()方法刪除最后一項(xiàng):
thisset = {"自行車", "汽車", "高鐵"}
x = thisset.pop()
print(x)
print(thisset)
注意: 集合是無(wú)序的,所以當(dāng)使用pop()方法時(shí),您將不知道刪除了哪個(gè)項(xiàng)。
示例
clear()方法清空集合:
thisset = {"自行車", "汽車", "高鐵"}
thisset.clear()
print(thisset)
示例
del關(guān)鍵字將刪除整個(gè)集合,包括集合自身:
thisset = {"自行車", "汽車", "高鐵"}
del thisset
print(thisset)
set()構(gòu)造方法
也可以使用set()構(gòu)造方法來(lái)創(chuàng)建集合。
示例
使用set()構(gòu)造方法創(chuàng)建集合:
thisset = set(("自行車", "汽車", "高鐵")) # 注意雙圓括號(hào)
print(thisset)
集合方法
Python有一組可以在set上使用的內(nèi)置方法。
方法
描述
add()
向集合中添加元素
clear()
從集合中移除所有元素
copy()
返回集合的副本
difference()
返回一個(gè)集合,該集合包含兩個(gè)或多個(gè)集合之間的差別項(xiàng)目
difference_update()
移除此集合中與另一個(gè)集合相同的項(xiàng)
discard()
刪除指定項(xiàng)
intersection()
返回一個(gè)集合,它是另外兩個(gè)集合的交集
intersection_update()
移除此集合中其他集合中不存在的項(xiàng)
isdisjoint()
返回兩個(gè)集合是否有交集
issubset()
返回另一個(gè)集合是否包含此集合
issuperset()
返回此集合是否包含另一個(gè)集合
pop()
從集合中移除一個(gè)元素
remove()
移除指定的元素
symmetric_difference()
返回具有兩個(gè)集合的對(duì)稱差異的集合
symmetric_difference_update()
插入來(lái)自這個(gè)集合和另一個(gè)集合的對(duì)稱差異
union()
返回包含集合并集的集合
update()
使用此集合和其他集合的并集更新集合
總結(jié)
以上是生活随笔為你收集整理的python集合用法_Python 集合(Set)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: win10无法修改密码:该系统对指定的账
- 下一篇: python词云安装什么库_python