我想从python中的字符串列表中删除所有空字符串。

我的想法是这样的:

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

还有什么更python化的方法吗?


当前回答

使用正则表达式和筛选器进行匹配

lstr = ['hello', '', ' ', 'world', ' ']
r=re.compile('^[A-Za-z0-9]+')
results=list(filter(r.match,lstr))
print(results)

其他回答

使用列表推导式是最python化的方式:

>>> strings = ["first", "", "second"]
>>> [x for x in strings if x]
['first', 'second']

如果列表必须就地修改,因为有其他引用必须看到更新的数据,那么使用slice赋值:

strings[:] = [x for x in strings if x]

使用正则表达式和筛选器进行匹配

lstr = ['hello', '', ' ', 'world', ' ']
r=re.compile('^[A-Za-z0-9]+')
results=list(filter(r.match,lstr))
print(results)

Filter实际上有一个特殊的选项:

filter(None, sequence)

它将过滤掉所有值为False的元素。这里不需要使用一个实际的可调用对象,比如bool, len等等。

它和map(bool,…)一样快

来自@Ib33X的回复太棒了。如果您想删除每个空字符串,剥离后。你还需要使用条带法。否则,如果字符串中有空格,它也会返回空字符串。比如," "对于这个答案也是有效的。所以,可以通过。

strings = ["first", "", "second ", " "]
[x.strip() for x in strings if x.strip()]

这个问题的答案是["first", "second"]。 如果你想用滤镜方法代替,你可以这样做 List (filter(lambda item: item.strip(), strings))。这是相同的结果。

你可以用这样的东西

test_list = [i for i in test_list if i]

其中test_list是要从中删除空元素的列表。