%20%E5%88%97%E8%A1%A8%E7%90%86%E8%A7%A3%E4%B8%AD%E9%9B%86%E5%90%88%E7%9A%84%E5%87%BD%E6%95%B8.png)
我遇到了以下程式碼來從清單中刪除重複項:
seen = set(); print [i for i in list if i not in seen and not seen.add(i)]
我無法理解到底是什麼“並沒有看到。「這部分程式碼的作用是幫助(設定。添加)給出以下解釋:
add(...)
Add an element to a set.
This has no effect if the element is already present.
期待您的幫助來理解它
答案1
列表理解迭代原始/輸入列表的值。我們希望當且僅當尚未看到一個值時將其新增至新/輸出清單中,因此條件表達式為if i not in seen
。當新值新增至新/輸出清單時,seen
必須更新該集合,因此seen.add(i)
需要更新函數。然而該set.add()
方法返回None
,其計算結果為False
。因此not
添加了該運算符,以便not seen.add(i)
始終返回True
。