我有一個字符串,我想查找包含「th」的單詞並將它們添加到列表中。但我不想要一個包含'T'的單詞。將單詞添加到包含字符串中某些字母的列表中
最終列表中不能有任何重複單詞。
thestring = "The character that can fire the. bullet that sheriff dodged"
a = "th"
b = "T"
def makelists(thestring, a, b)
"""
>>> makelists(thestring, 'th', 'T')
['that', 'the.']
"""
到目前爲止,我只有這個,它打印出重複的單詞。
def makelists(thestring, a, b)
words = thestring.split()
thelist = []
for word in words:
if a in word:
thelist.append(word)
for char in thelist:
if b in char:
thelist.remove(char)
print thelist
我得到的輸出是['that','the','that']。
什麼編輯可以做我的代碼爲這一個輸出爲[「那個」,「了。」]
爲什麼不使用一套? – devnull
您可以簡單地將'thelist'設置爲['Set'](https://docs.python.org/2/c-api/set.html),然後爲您處理重複項。 –
'set(i for thestring.split()if a in i)' – devnull