可以請某人用簡單的 for 回圈和陳述句撰寫以下串列理解。
new_words = ' '.join([word for word in line.split() if not
any([phrase in word for phrase in char_list])])
我在下面的代碼中寫了上面的串列理解,但它不起作用。
new_list = []
for line in in_list:
for word in line.split():
for phrase in char_list:
if not phrase in word:
new_list.append(word)
return new_list
謝謝
uj5u.com熱心網友回復:
new_words = ' '.join(
[
word for word in line.split()
if not any(
[phrase in word for phrase in char_list]
)
]
)
或多或少相當于:
new_list = []
for word in line.split():
phrases_in_word = []
for phrase in char_list:
# (phrase in word) returns a boolean True or False
phrases_in_word.append(phrase in word)
if not any(phrases_in_word):
new_list.append(word)
new_words = ' '.join(new_list)
uj5u.com熱心網友回復:
new_words = ' '.join([word for word in line.split()
if not any([phrase in word for phrase in char_list])])
相當于:
lst = []
for word in line.split():
for phrase in char_list:
if phrase in word:
break
else: # word not in ANY phrase
lst.append(word)
new_words = ' '.join(lst)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322293.html
上一篇:如何將大型嵌套集拆分為單獨的集?
下一篇:檢查串列是否包含用戶輸入的字串
