1

我正在尝试使用另一个列表作为参考从列表中的项目中删除特定字符。目前我有:

forbiddenList = ["a", "i"]
tempList = ["this", "is", "a", "test"]
sentenceList = [s.replace(items.forbiddenList, '') for s in tempList]
print(sentenceList)

我希望能打印出来:

["ths", "s", "test"]

当然,禁止列表非常小,我可以单独替换每个,但是当我有大量“禁止”项目时,我想知道如何“正确”执行此操作。

4

2 回答 2

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']
于 2015-05-04T19:00:58.320 回答
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']

str.translate这是一个使用and的 Python 3 解决方案str.maketrans。它应该很快。

您也可以在 Python 2 中执行此操作,但接口str.translate略有不同:

>>> 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']
于 2015-05-04T19:44:05.713 回答