亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Python 集合(Sets)2

访问项

您无法通过引用索引或键来访问集合中的项。但是,您可以使用for循环遍历集合项,或者使用in关键字检查集合中是否存在指定的值。

示例,遍历集合并打印值:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

示例,检查集合中是否存在 “banana”:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Python - 添加集合项

一旦创建了集合,您就不能更改其项,但可以添加新项。要向集合添加一个项,请使用add()方法。

示例,使用add()方法向集合添加一个项:

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

要将另一个集合中的项添加到当前集合中,请使用update()方法。

示例,将tropical中的元素添加到thisset中:

thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

添加任何可迭代对象

update()方法中的对象不必是集合,可以是任何可迭代对象(元组、列表、字典等)。

示例,将列表的元素添加到集合中:

thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Python - 删除集合项

要删除集合中的项,可以使用remove()discard()方法。

示例,使用remove()方法删除 “banana”:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

注意:如果要删除的项不存在,remove()将引发错误。

示例,使用discard()方法删除 “banana”:

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

注意:如果要删除的项不存在,discard()不会引发错误。

您还可以使用pop()方法来删除一个项,但此方法将删除一个随机项,因此不能确定删除哪个项。pop()方法的返回值是已删除的项。

示例,使用pop()方法删除一个随机项:

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

注意:由于集合是无序的,因此在使用pop()方法时无法确定删除哪个项。

示例,clear()方法将清空集合:

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

示例,del关键字将完全删除集合:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

Python - 遍历集合

您可以使用for循环遍历集合项:

示例,遍历集合并打印值:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

希望这些信息对您有所帮助!如果有任何问题或需要更多解释,请随时提问。

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消