代码之家  ›  专栏  ›  技术社区  ›  Simon D

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

  •  17
  • Simon D  · 技术社区  · 17 年前

    6 回复  |  直到 17 年前
        1
  •  25
  •   Wojciech Bederski    17 年前
    next(s for s in list_of_string if s)
    

    多亏了 Stephan202 对于这个Python 3版本。

        2
  •  6
  •   sykora    17 年前

    为了移除所有空字符串,

    [s for s in list_of_strings if s]

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

        3
  •  3
  •   SilentGhost    17 年前
    def get_nonempty(list_of_strings):
        for s in list_of_strings:
            if s:
                return s
    
        4
  •  3
  •   Steve Losh    17 年前

    这里有一条捷径:

    filter(None, list_of_strings)[0]
    

    编辑:

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

    from itertools import ifilter
    ifilter(None, list_of_strings).next()
    
        5
  •  0
  •   ghostdog74    17 年前

    arr = ['','',2,"one"]
    for i in arr:
        if i:
            print i
            break
    
        6
  •  0
  •   yason yason    17 年前

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

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

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