t = ['is', 'are', 'was', 'the', 'he', 'she', 'fox', 'jumped']
s = "He was walking down the road."
new = []
for word in phrase.split():
if word.lower() in filters:
new.append(word)
else:
new.extend(word)
new.append(' ')
print new[:-1] # We slice the last element because it is ' '.
印刷:
['He', ' ', 'was', ' ', 'w', 'a', 'l', 'k', 'i', 'n', 'g', ' ', 'd', 'o', 'w', 'n', ' ', 'the', ' ', 'r', 'o', 'a', 'd', '.']
作为一个函数:
def filter_down(phrase, filters):
new = []
for word in phrase.split():
if word.lower() in filters:
new.append(word)
else:
new.extend(list(word)) # list(word) is ['w', 'a', 'l', 'k', 'i', 'n', 'g']
new.append(' ')
return new