我想从python中的字符串列表中删除所有空字符串。
我的想法是这样的:
while '' in str_list:
str_list.remove('')
还有什么更python化的方法吗?
我想从python中的字符串列表中删除所有空字符串。
我的想法是这样的:
while '' in str_list:
str_list.remove('')
还有什么更python化的方法吗?
当前回答
为了消除空字符串,我将使用if x != "而不是if x。是这样的:
str_list = [x for x in str_list if x != '']
这将在列表中保留None数据类型。此外,如果您的列表中有整数,0是其中之一,它也将被保留。
例如,
str_list = [None, '', 0, "Hi", '', "Hello"]
[x for x in str_list if x != '']
[None, 0, "Hi", "Hello"]
其他回答
我会使用滤镜:
str_list = filter(None, str_list)
str_list = filter(bool, str_list)
str_list = filter(len, str_list)
str_list = filter(lambda item: item, str_list)
Python 3从filter返回一个迭代器,因此应该包装在调用list()中
str_list = list(filter(None, str_list))
>>> lstr = ['hello', '', ' ', 'world', ' ']
>>> lstr
['hello', '', ' ', 'world', ' ']
>>> ' '.join(lstr).split()
['hello', 'world']
>>> filter(None, lstr)
['hello', ' ', 'world', ' ']
比较的时间
>>> from timeit import timeit
>>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
4.226747989654541
>>> timeit('filter(None, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
3.0278358459472656
注意,filter(None, lstr)不会删除带有空格''的空字符串,它只会删除'',而'' .join(lstr).split()会删除两者。
要使用filter()删除空白字符串,需要更多的时间:
>>> timeit('filter(None, [l.replace(" ", "") for l in lstr])', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
18.101892948150635
使用列表推导式是最python化的方式:
>>> strings = ["first", "", "second"]
>>> [x for x in strings if x]
['first', 'second']
如果列表必须就地修改,因为有其他引用必须看到更新的数据,那么使用slice赋值:
strings[:] = [x for x in strings if x]
正如Aziz Alto过滤器(None, lstr)所报道的那样,不会用空格' '删除空字符串,但如果你确定lstr只包含字符串,则可以使用过滤器(str.;)地带,lstr)
>>> lstr = ['hello', '', ' ', 'world', ' ']
>>> lstr
['hello', '', ' ', 'world', ' ']
>>> ' '.join(lstr).split()
['hello', 'world']
>>> filter(str.strip, lstr)
['hello', 'world']
在我的电脑上比较时间
>>> from timeit import timeit
>>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
3.356455087661743
>>> timeit('filter(str.strip, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
5.276503801345825
最快的解决方案删除“和空字符串的空格''保留'' .join(lstr).split()。
正如在评论中报告的那样,如果字符串包含空格,情况就不同了。
>>> lstr = ['hello', '', ' ', 'world', ' ', 'see you']
>>> lstr
['hello', '', ' ', 'world', ' ', 'see you']
>>> ' '.join(lstr).split()
['hello', 'world', 'see', 'you']
>>> filter(str.strip, lstr)
['hello', 'world', 'see you']
你可以看到过滤器(str。Strip, lstr)保留带有空格的字符串,但' '.join(lstr).split()将分割该字符串。
为了消除空字符串,我将使用if x != "而不是if x。是这样的:
str_list = [x for x in str_list if x != '']
这将在列表中保留None数据类型。此外,如果您的列表中有整数,0是其中之一,它也将被保留。
例如,
str_list = [None, '', 0, "Hi", '', "Hello"]
[x for x in str_list if x != '']
[None, 0, "Hi", "Hello"]