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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1138024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:33:33  来源:igfitidea点击:

Get first non-empty string from a list in python

pythonstringlist

提问by Simon D

In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string?

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

回答by Wojciech Bederski

next(s for s in list_of_string if s)

Edit: py3k proof version as advised by Stephan202 in comments, thanks.

编辑:按照 Stephan202 在评论中的建议,py3k 证明版本,谢谢。

回答by sykora

To remove all empty strings,

要删除所有空字符串,

[s for s in list_of_strings if s]

[s for s in list_of_strings if s]

To get the first non-empty string, simply create this list and get the first element, or use the lazy method as suggested by wuub.

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

回答by SilentGhost

def get_nonempty(list_of_strings):
    for s in list_of_strings:
        if s:
            return s

回答by Steve Losh

Here's a short way:

这是一个简短的方法:

filter(None, list_of_strings)[0]

EDIT:

编辑:

Here's a slightly longer way that is better:

这是一个稍微长一点的更好的方法:

from itertools import ifilter
ifilter(None, list_of_strings).next()

回答by Steve Losh

Based on your question I'll have to assume a lot, but to "get" the first non-empty string:

根据您的问题,我必须假设很多,但要“获取”第一个非空字符串:

(i for i, s in enumerate(x) if s).next()

which returns its index in the list. The 'x' binding points to your list of strings.

它返回它在列表中的索引。'x' 绑定指向您的字符串列表。

回答by ghostdog74

to get the first non empty string in a list, you just have to loop over it and check if its not empty. that's all there is to it.

要获取列表中的第一个非空字符串,您只需遍历它并检查它是否不为空。这里的所有都是它的。

arr = ['','',2,"one"]
for i in arr:
    if i:
        print i
        break