簡體   English   中英

Python 3.5.2:檢查字符串中的字符形成一個列表,與使用!=檢查不同

[英]Python 3.5.2 : Checking characters in a string form a list not the same as checking using !=

我想編寫一個過濾字符串中的字母“ m”或“ M”的程序。 使用此版本時:

sentence = "Therem are a lotm of Ms in here andm iM hope tmo find then amll"
not_good = ["m", "M"]
result = list(filter(lambda x : x not in not_good,sentence))
result1 = "".join(result)
print(result1)

給我我想要的東西: There are a lot of s in here and i hope to find then all

當我嘗試此版本的代碼時:

sentence = "Therem are a lotm of Ms in here andm iM hope tmo find then amll"

result = list(filter(lambda x : x != "m" or x != "M" ,sentence))

result1 = "".join(result)

print(result1)

它印出一句話: Therem are a lotm of Ms in here andm iM hope tmo find then amll

另外,如果我想使用此代碼制作僅包含“ m”和“ M”的字符串:

result = list(filter(lambda x : x == "m" or x == "M" ,sentence))
result1 = "".join(result)
print(result1)

它工作得很好。 我得到了: mmMmMmm

為什么第二個版本的代碼沒有完成而第一個版本的工作呢? 另外,雖然==有效,但為什么不!=

也許我不能使用=! 搜索一個字符串? 不要這樣...

請幫助初學者程序員!

而且英語不是我的母語,所以我很抱歉有任何錯誤。

您應該在中使用and而不是or

result = list(filter(lambda x : x != "m" and x != "M" ,sentence))

x != "m" or x != "M"對於任何字符始終為True。

您想要的是條件x == "m" or x == "M"的求逆,而在那種情況下,您可以不這樣做not (x == "m" or x == "M")

至於為什么x != "m" or x != "M"不能按您想要的方式工作,您可以看到,如果x為m ,x顯然不是M ,那么條件為True,因此字符將通過通過過濾器,最終得到結果。

一種更正式的表達方式是通過De Morgan定律 ,但簡而言之,在這種情況下:

not (x == "m" or x == "M") -> (x == "m" and x == "M")

同樣對於我們原來的錯誤案例; 雖然不是我們想要的,但以下表達式是相同的。

(x != "m" or x != "M") -> not (x != "m" and x != "M")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM