【问题标题】:Is there a neater way to get the first occurrence of something?有没有一种更简洁的方法来获得第一次出现的东西?
【发布时间】:2023-03-17 19:55:01
【问题描述】:

我有一个包含许多东西的列表:

lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']

我想获取列表中满足谓词的第一项,例如len(item) > 2。有没有比 itertools 的 dropwhile 和 next 更简洁的方法?

first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista))

一开始我确实使用了[item for item in lista if len(item)&gt;2][0],但这需要python首先生成整个列表。

【问题讨论】:

    标签: python iterator itertools


    【解决方案1】:
    >>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
    >>> next(i for i in lista if len(i) > 2)
    'foo'
    

    【讨论】:

    • 请注意,下一个功能是在 2.6 中添加的。如果您需要与 2.5 或 2.4 兼容,请使用 (i for i in lista if len(i) &gt; 2).next()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2019-12-27
    • 2021-07-24
    • 2011-12-30
    • 2017-05-20
    • 2013-03-27
    相关资源
    最近更新 更多