【问题标题】:python how can return first value = true in a list? [duplicate]python如何在列表中返回第一个值= true? [复制]
【发布时间】:2016-03-24 19:08:21
【问题描述】:

像这样:
如果列表是['', 'a', 'b'],则返回'a'
如果列表是['', '', ''],则返回''
如果列表是['a', 'b', 'c'],则返回a
python中有什么方法可以做到这一点吗?
我的意思是不需要我自己编写函数
我想要一个像var a = b || c in javascript 这样的内置方法

【问题讨论】:

标签: python


【解决方案1】:

明显的方法是使用生成器表达式

>>> next(x for x in ['a', 'b', 'c'] if x)
'a'
>>> next(x for x in ['', 'b', 'c'] if x)
'b'

但是 - 所有 False 都会引发异常而不是 ''

>>> next(x for x in ['', '', ''] if x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

您可以通过像这样为next 提供默认值来解决此问题

>>> next((x for x in ['', '', ''] if x), '')
''

【讨论】:

    【解决方案2】:

    直接来自itertools recipes,Python 认可的解决方案(如果您使用的是 Py2,请将 filter 替换为 itertools.ifilter 否则不会正确短路):

    def first_true(iterable, default=False, pred=None):
        """Returns the first true value in the iterable.
    
        If no true value is found, returns *default*
    
        If *pred* is not None, returns the first item
        for which pred(item) is true.
    
        """
        # first_true([a,b,c], x) --> a or b or c or x
        # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
        return next(filter(pred, iterable), default)
    

    【讨论】:

      【解决方案3】:

      我想要一个像 var a = b || 这样的内置方法javascript中的c

      Python 的 or 的工作方式几乎完全相同,所以如果你用 Javascript 编写它

      result = arr[0] || arr[1] || arr[2];
      

      然后您可以在 Python 中执行以下操作:

      result = l[0] or l[1] or l[2]
      

      【讨论】:

        【解决方案4】:

        这是使用max 的一种不同寻常的方式。

        >>> max(['a', 'b', 'c'], key=bool)
        'a'
        >>> max(['', 'b', 'c'], key=bool)
        'b'
        >>> max(['', '', ''], key=bool)
        ''
        

        缺点是不会短路

        【讨论】:

        • key=bool 也可以(我的意思是,max 不是min--但总体思路相同)
        • @DSM,对学校来说太酷了:)
        • 是的,正如我编辑澄清的那样,您需要改为 max
        猜你喜欢
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-12
        • 1970-01-01
        • 1970-01-01
        • 2019-05-28
        • 1970-01-01
        相关资源
        最近更新 更多