我正在努力理解下面的列表理解



谁能用简单的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

感谢
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)
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)

最新更新