[英]comparing a list of tuples python
我在 python 中有一個[(word, sym) , (word, sym)....]
形式的元組列表。
讓我們假設符號是A
或B
。 我想返回列表中包含("example", A)
和("example", B)
形式的兩個元組的所有單詞。 所以基本上一個詞與A
和B
配對。 我假設這可以使用列表理解來完成。 我可以這樣做來獲取符號為 A 的所有單詞:
[x[0] for x in self.list if x[1] == "A"]
並以類似的方式獲取符號為 B 的單詞列表,但是我不確定如何比較這兩個列表。
我會簡單地使用if word in listA and word in listB
嗎?
假設順序不重要,這是set
交集的一個很好的用例:
setA = {word for word, sym in self.list if sym == "A"}
setB = {word for word, sym in self.list if sym == "B"}
AB_words = setA & setB # Preserves only those words found in both input sets
然后如果你需要測試任何給定的詞是否是一個常用詞,這是一個簡單的set
成員測試:
if word in AB_words:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.