我想从python中的字符串列表中删除所有空字符串。
我的想法如下:
while '' in str_list:
str_list.remove('')
有没有更多的Python方式可以做到这一点?
#1楼
代替if x,我将使用if X!=”来消除空字符串。 像这样:
str_list = [x for x in str_list if x != '']
这将在列表中保留“无”数据类型。 另外,如果您的列表包含整数,并且0是其中的一个,那么它也会被保留。
例如,
str_list = [None, '', 0, "Hi", '', "Hello"]
[x for x in str_list if x != '']
[None, 0, "Hi", "Hello"]
#2楼
>>> 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
#3楼
str_list = ['2', '', '2', '', '2', '', '2', '', '2', '']
for item in str_list:
if len(item) < 1:
str_list.remove(item)
简短而甜美。
#4楼
filter(None, str)不会删除空格为''的空字符串,它只会删除'和''。
join(str).split()删除两者。 但是,如果您的list元素有空间,那么它将更改您的list元素,因为它首先连接了list的所有元素,然后按空格将它们吐出来,因此您应该使用:-
str = ['hello', '', ' ', 'world', ' ']
print filter(lambda x:x != '', filter(lambda x:x != ' ', str))
它会同时删除这两个元素,并且不会影响您的元素,例如:-
str = ['hello', '', ' ', 'world ram', ' ']
print ' '.join(lstr).split()
print filter(lambda x:x != '', filter(lambda x:x != ' ', lstr))
输出:-
['hello','world','ram']
['hello','world ram']
#5楼
strings = ["first", "", "second"]
[x for x in strings if x]
输出: ['first', 'second']