在满足条件之前迭代列表的最pythonic方法是什么? [英] What is the most pythonic way to iterate over a list until a condition is met?

查看:98
本文介绍了在满足条件之前迭代列表的最pythonic方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实际值列表:

values = [0.1, 2.9, 1.4, 5.7, 9.2, 3.8]

我希望迭代项目的数量,直到满足某些条件为止.例如,如果条件为item > 5,则结果为3.

I want to have the number of items iterated over, until some condition was met. For example, if the condition was item > 5, the result would be 3.

最简单,最直接的方法是:

The easiest way, and perhaps most straight-forward way to do this would be:

for index, item in enumerate(values):
    if (item > 5):
        print(index)
        break

还有其他方法更多pythonic,最好是单行吗?

推荐答案

您可以将itertools.takewhilesum结合使用,该元素将使用元素,直到满足条件为止,并使用我们懒惰地求值的生成器表达式:

You can use itertools.takewhile with sum which will take elements until the condition is met, using a generator expression we lazily evaluate:

values = [0.1, 2.9, 1.4, 5.7, 9.2, 3.8]

from itertools import takewhile

print(sum(1 for _ in takewhile(lambda x: x< 5,values)))

这篇关于在满足条件之前迭代列表的最pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆