![](/img/trans.png)
[英]Runtime difference between set.discard and set.remove methods in Python?
[英]Why set.discard doesn't throw an error when a set is passed to it in Python?
我的問題很簡單。
當我跑步時
someSet = {1,2,3,4}
someSet.discard([5])
它給出了錯誤:
Traceback (most recent call last):
File "File.py", line 2, in <module>
someSet.discard([5])
TypeError: unhashable type: 'list'
就像列表一樣,集合也是不可散列的,不能存儲在集合中。 因此,我預計以下代碼會產生錯誤:
someSet = {1,2,3,4}
someSet.discard({5})
但令我驚訝的是,它沒有產生任何錯誤。 為什么會這樣? 這是否意味着我收到 list 錯誤,因為除了無法散列之外還有其他原因導致錯誤? 如果是,那么那是什么東西?
有一個奇怪的特殊情況,如果您將另一個集合傳遞給set.remove
、 set.discard
或x in set
,該集合將自動轉換為 frozenset。
請注意,
__contains__()
、remove()
和discard()
方法的elem參數可能是一個集合。 為了支持搜索等效的 frozenset,從elem創建了一個臨時的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.