[英]how to remove characters from items in a list, using another list as reference
我正在尝试使用另一个列表作为参考从列表中的项目中删除特定字符。 目前我有:
forbiddenList = ["a", "i"]
tempList = ["this", "is", "a", "test"]
sentenceList = [s.replace(items.forbiddenList, '') for s in tempList]
print(sentenceList)
我希望可以打印出来:
["ths", "s", "test"]
当然,禁止清单非常小,我可以单独替换每个清单,但是当我有大量“禁止”物品清单时,我想知道如何“适当”进行此操作。
您可以使用嵌套列表推导。
>>> [''.join(j for j in i if j not in forbiddenList) for i in tempList]
['ths', 's', '', 'test']
似乎您还想删除如果元素为空的元素(例如,所有字符都在forbiddenList
)? 如果是这样,您可以将整个内容包装在另一个list comp中(以提高可读性为代价)
>>> [s for s in [''.join(j for j in i if j not in forbiddenList) for i in tempList] if s]
['ths', 's', 'test']
>>> 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
和str.maketrans
的Python 3解决方案。 应该很快。
您也可以在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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.