简体   繁体   中英

What's the fastest way to eliminate all instances of a string from a list with Python?

lst = ['A','B','A','B','O','O','O']

lst.remove('O')
lst
['A','B','A','B','O','O']

What is the fastest way to eliminate all instances of 'O' from a list, since list.remove() only eliminate one? Basically is there a shorter way to write lst = [ele for ele in lst if not ele=='O'] ?

You can use filter, as an alternative (even though list comprehension that you provided, is probably the best way):

list(filter(lambda x: x!='O', lst))

Another alternative, that will only work for a list of single strings, as is your example (it will not work for longer texts though) is the following:

list(''.join(lst).replace('O', ''))

The above are some ideas, i cannot guarantee that are faster/more efficient

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM