![](/img/trans.png)
[英]Using for / list comprehension for creating a tuple from any amount of other tuples
[英]cannot remove a tuple from list of tuples using list comprehension
我有一個元組列表,我想從該列表中刪除一個元素。 我不想使用remove()
方法,因為列表不是唯一的,並且我想刪除所有與給定元組匹配的元素。
那么,為什么下面的代碼不刪除(21, 187)
元素?
edgeList = [(1, 2), (3, 75), (21, 187), (2, 6)]
edgeList = [(e1, e2) for e1, e2 in edgeList if (e1 != 21 & e2 != 187)]
print(edgeList)
上面的代碼將打印:
[(1, 2), (3, 75), (21, 187), (2, 6)]
為什么元組(21, 187)
仍然在那里?
您正在使用位運算符&
,要使用and
:
edgeList = [(e1,e2) for e1,e2 in edgeList if (e1!=21 and e2!=187)]
問題在於&
的優先級與and
優先級不同,因此您最終會執行e1 != (21 & e2) != 187
Francisco的答案正確指出了您的問題之所以出現,是因為比較(例如!=
)的優先級低於按位布爾運算符(例如&
),但是優先級高於邏輯布爾運算符(例如and
)。 您也可以通過執行以下操作來完全避免該問題
[e for e in edgeList if e != (21, 187)]
如果所有元組的元素比較相等,則python中的元組比較相等。
如果將每個不等式檢查放在括號中&
則可以使用&
: edgeList = [(e1,e2) for e1,e2 in edgeList if ((e1!=21) & (e2!=187))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.