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

我的想法是这样的:

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

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


当前回答

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

filter(None, sequence)

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

它和map(bool,…)一样快

其他回答

根据列表的大小,使用list.remove()而不是创建一个新列表可能是最有效的:

l = ["1", "", "3", ""]

while True:
  try:
    l.remove("")
  except ValueError:
    break

这样做的优点是不需要创建一个新的列表,但缺点是每次都必须从头搜索,尽管不像上面所建议的在l中使用while“每次只需要搜索一次”(当然有一种方法可以保持两种方法的优点,但它更复杂)。

正如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()将分割该字符串。

你可以用这样的东西

test_list = [i for i in test_list if i]

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

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

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

我会使用滤镜:

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))