从python中的列表中获取第一个非空字符串

Sim*_*n D 10 python string list

在Python中,我有一个字符串列表,其中一些可能是空字符串.获得第一个非空字符串的最佳方法是什么?

Woj*_*ski 21

next(s for s in list_of_string if s)
Run Code Online (Sandbox Code Playgroud)

编辑:由Stephan202在评论中建议的py3k校对版,谢谢.

  • 顺便说一句,如果所有字符串都为空,它将引发`StopIteration`. (3认同)
  • 为了避免处理`StopIteration`,可以使用[`next()`](https://docs.python.org/2/library/functions.html#next)的双参数版本来指定回退value:`next((s表示在list_of_strings中为s),'not found')` (3认同)
  • py3k版本:`next(如果是s则为list_of_string中的s)`. (2认同)

syk*_*ora 5

要删除所有空字符串,

[s for s in list_of_strings if s]

要获取第一个非空字符串,只需创建此列表并获取第一个元素,或使用wuub建议的惰性方法.

  • 但是效率有点低!如果你只有空的一百万非空蜇,你将花费时间和内存生成一百万字符串的列表,只是为了得到第一个...至少,使用一个发电机! (5认同)