我正在嘗試運行一個簡單的 python 腳本,該腳本洗掉包含某些字母的某些單詞,這些單詞最初是字串的一部分,正確地分隔成單詞串列。我多次重新檢查代碼,但結果是錯誤的。什么需要改變,因為我相信代碼是正確的。請幫忙。
s = """aline amine
avine azine
brine chine
cline coine
crine daine
dwine exine
ezine faine
feine foine
gwine imine
koine laine
Maine opine
ovine peine
quine raine
rhine saine
seine shine
spine swine
thine trine
tsine twine
Udine urine
whine"""
words = list(s.split())
for i in words:
if "s" in i:
words.remove(i)
elif "a" in i:
words.remove(i)
elif "d" in i:
words.remove(i)
elif "w" in i:
words.remove(i)
elif "u" in i:
words.remove(i)
print(words)
uj5u.com熱心網友回復:
一般來說,在迭代串列時從串列中洗掉元素是一個壞主意,因為當您嘗試訪問它時記憶體正在移動。
相反,創建一個新串列(使用串列推導),只保留不包含任何禁止字母的單詞(使用 來檢查單詞是否包含字母in,我們使用 將其推廣到多個字母map())。
words = s.split()
result = [word for word in words if not any(map(lambda x: x in word, "adsuw"))]
uj5u.com熱心網友回復:
您還可以使用filter過濾給定條件的串列的功能。
def criterion(str_):
# Returns True if str_ has none of the characters in list_
# Returns False otherwise
return all(c not in str_ for c in list_)
words = s.split()
list_ = ['s', 'a', 'd', 'w', 'u']
# also works: list_ = 'sadwu'
result = list(filter(criterion, words))
或者,在一行中:
result = list(filter(lambda str_: all(c not in str_ for c in 'sadwu'), s.split()))
uj5u.com熱心網友回復:
這也可以完成這項作業:
words = s.split()
ex = ["s", "a", "d", "w", "u"]
words = [i for i in words if all(e not in i for e in ex)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439279.html
