I am trying to remove specific characters from items in a list, using another list as a reference. Currently I have:
forbiddenList = ["a", "i"]
tempList = ["this", "is", "a", "test"]
sentenceList = [s.replace(items.forbiddenList, '') for s in tempList]
print(sentenceList)
which I hoped would print:
["ths", "s", "test"]
of course, the forbidden list is quite small and I could replace each individually, but I would like to know how to do this "properly" for when I have an extensive list of "forbidden" items.
You could use a nested list comprehension.
>>> [''.join(j for j in i if j not in forbiddenList) for i in tempList]
['ths', 's', '', 'test']
It seems like you also want to remove elements if they become empty (as in, all of their characters were in forbiddenList
)? If so, you can wrap the whole thing in even another list comp (at the expense of readability)
>>> [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']
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.