如何使用另一个列表作为参照从列表中的项目中删除字符

2024-10-03 13:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我希望能打印出来:

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

当然,禁地名单是相当小的,我可以取代每一个单独,但我想知道如何做到这一点“适当”的时候,我有一个广泛的“禁地”项目清单。你知道吗


Tags: 项目intest列表forisitemsthis
2条回答
>>> 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']

这是一个使用^{}^{}的python3解决方案。应该很快。你知道吗

您也可以在Python 2中执行此操作,但是^{}的接口略有不同:

>>> 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']

可以使用嵌套列表。你知道吗

>>> [''.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']

相关问题 更多 >