我有一個名為“list”的串列,它包含大約 20K 個字串,我需要從中洗掉其中包含“text”:“”的元素。
我正在創建一個像這樣的新清理串列
clean_list = []
for i in list:
if '"text": ""' in i == False:
clean_list.append(i)
print(i)
但是元素不附加并且 clean_list 是空的。可能是什么問題?回圈是錯誤的。
我還能如何擺脫串列中的某些元素?
uj5u.com熱心網友回復:
這不起作用的原因是操作員沒有按照您認為的方式進行關聯:
>>> '"text": ""' in "foo" == False
False
>>> ('"text": ""' in "foo") == False
True
在任何情況下,使用in ... == False都是笨拙的/不符合 Python 的;最好做的更自然not in ...:
>>> '"text": ""' not in "foo"
True
uj5u.com熱心網友回復:
if '"text": ""' in i == False:
不要使用那種語法。這i == False是不必要的(并且看起來很尷尬),在這種特定情況下,它實際上會導致您遇到的問題。
請改用此語法:
if '"text": ""' not in i:
如果您想知道為什么會發生這種情況,請繼續閱讀。
這個問題是由于operator chaining造成的。
當您的運算式包含兩個(或更多)運算子時,例如:
a < b < c
Python 將該運算式視為您輸入了以下內容:
a < b and b < c
在您的示例中,inand==都是運算子,因此 Python 將您的運算式視為您輸入了以下內容:
if '"text": ""' in i and i == False:
第一部分是真的,但第二部分不是。所以這個運算式作為一個整體是錯誤的。
uj5u.com熱心網友回復:
首先,您不應該使用 list 等受保護的關鍵字來命名變數。
對于您的用例,您可以使用串列理解:
clean_list = [string for string in list if '"text": ""' not in string]
uj5u.com熱心網友回復:
你不應該在 Python 中使用內置的命名為變數名。
s = 'This is a sample "text": "" and it should not have it.'
if r'"text": ""' in s:
print("Found.")
The output will be `Found.`
現在,借助它,您可以使用:
clean_list = [i for i in list if r'"text": ""' not in i]
# This just creates a new list if an item `i` is found not having the pattern '"text": ""'. The r' refers to raw strings and can be helpful when using a lot of symbols and characters.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439253.html
上一篇:我的目標是在我的串列中列印隨機專案(大寫)。列印該專案后,如何從串列中洗掉該專案以使其無法重復?
下一篇:從字典值中獲取子字串
