How do I erase an empty string from the list?

Asked 2 years ago, Updated 2 years ago, 176 views

How do I erase all the empty strings in the list elements? I want to make better chords than the ones I wrote Please tell me more Python-like chords

while '' in str_list:
    str_list.remove('')

string list python

2022-09-22 22:28

1 Answers

str_list = filter(None, str_list) #Fast
str_list = filter(bowl, str_list) # Fast
str_list = filter(len, str_list) #Slightly slow
str_list = filter(lambda item: item, str_list) # list slower than compression

If you compare the speeds of the four methods, you will see the following:

>>> timeit('filter(None, str_list)', 'str_list=["a"]*1000', number=100000)
2.4797441959381104
>>> timeit('filter(bool, str_list)', 'str_list=["a"]*1000', number=100000)
2.4788150787353516
>>> timeit('filter(len, str_list)', 'str_list=["a"]*1000', number=100000)
5.2126238346099854
>>> timeit('[x for x in str_list if x]', 'str_list=["a"]*1000', number=100000)
13.354584932327271
>>> timeit('filter(lambda item: item, str_list)', 'str_list=["a"]*1000', number=100000)
17.427681922912598
strings = ["first", "", "second"]
[x for x in strings if x]


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.