在Python中,我有一个字符串列表,其中一些字符串可能为空字符串。获取第一个非空字符串的最佳方法是什么?
next(s for s in list_of_string if s)
感谢Stephan202提供的Python 3版本。
StopIteration
异常。 - SilentGhostStopIteration
,可以使用next()
函数的两个参数版本来指定备用值:next((s for s in list_of_strings if s), 'not found')
。其中s
为字符串列表中的元素,如果有元素存在则返回第一个元素,否则返回指定的备用值'not found'
。 - matts要删除所有空字符串,可以使用以下代码:
[s for s in list_of_strings if s]
如果要获取第一个非空字符串,可以创建该列表并获取其第一个元素,或者使用wuub建议的惰性方法。
def get_nonempty(list_of_strings):
for s in list_of_strings:
if s:
return s
filter(None, list_of_strings)[0]
编辑:
这里有一种稍微复杂但更好的方法:
from itertools import ifilter
ifilter(None, list_of_strings).next()
filter
会遍历整个列表,而不考虑内容。在py3k中,filter
返回一个不可订阅的过滤器对象。 - Stephan202next(filter(None, list_of_strings))
。(无需导入。) - Stephan202要获取列表中第一个非空字符串,只需循环遍历并检查其是否为空即可。就是这么简单。
arr = ['','',2,"one"]
for i in arr:
if i:
print i
break
根据您的问题,我需要做出很多假设,但是要“获取”第一个非空字符串:
(i for i, s in enumerate(x) if s).next()
该函数返回列表中字符串的索引。'x'绑定指向您的字符串列表。