我正在尝试从列表中的项目中删除特定字符,使用另一个列表作为参考。目前我有:
forbiddenList = ["a", "i"]
tempList = ["this", "is", "a", "test"]
sentenceList = [s.replace(items.forbiddenList, '') for s in tempList]
print(sentenceList)
我希望打印出来:
["ths", "s", "test"]
当然,禁止列表非常小,我可以单独替换每个,但我想知道如何“正确”地执行此操作,因为我有一个“禁止”项目的广泛列表。
答案 0 :(得分:3)
您可以使用嵌套列表理解。
>>> [''.join(j for j in i if j not in forbiddenList) for i in tempList]
['ths', 's', '', 'test']
如果元素变空(例如,所有字符都在forbiddenList
中),您似乎也想删除它们?如果是这样,你可以将整个事物包装在另一个列表中(以可读性为代价)
>>> [s for s in [''.join(j for j in i if j not in forbiddenList) for i in tempList] if s]
['ths', 's', 'test']
答案 1 :(得分:1)
>>> templist = ['this', 'is', 'a', 'test']
>>> forbiddenlist = ['a', 'i']
>>> trans = str.maketrans('', '', ''.join(forbiddenlist))
>>> [w for w in (w.translate(trans) for w in templist) if w]
['ths', 's', 'test']
This is a Python 3 solution using str.translate
and str.maketrans
. It should be fast.
You can also do this in Python 2, but the interface for str.translate
is slightly different:
>>> templist = ['this', 'is', 'a', 'test']
>>> forbiddenlist = ['a', 'i']
>>> [w for w in (w.translate(None, ''.join(forbiddenlist))
... for w in templist) if w]
['ths', 's', 'test']