# python matplotlib设置坐标轴刻度大小 - 从符合条件的迭代中获取第一个项目

`next(x for x in the_iterable if x > 3)`

`next( (x for x in the_iterable if x>3), default_value)`

matplotlib标注 plot虚线

``````def first(the_iterable, condition = lambda x: True):
for i in the_iterable:
if condition(i):
return i
``````

``````>>> first(range(10))
0
>>> first(range(10), lambda i: i > 3)
4
``````

``````>>> (x for x in xrange(10) if x > 5).next()
6
``````

``````>>> foo = None
>>> for foo in (x for x in xrange(10) if x > 5): break
...
>>> foo
6
``````

``````(x for x in range(10) if x > 3).next()
``````

``````next(x for x in xrange(10) if x > 3)
``````

``````(lambda x:x[0] if x else None)(list(y for y in ITERABLE if CONDITION))
``````

（如果没有元素匹配，您将得到`None`而不是`StopIteration`异常。）

Python 3中最有效的方式是以下方法之一（使用类似的例子）：

## 用“理解”风格：

``````next(i for i in range(100000000) if i == 1000)
``````

## 具有“功能性”风格：

``````next(filter(lambda i: i == 1000, range(100000000)))
``````

## 默认值

### “功能性”风格：

``````next(filter(lambda i: i == 1000, range(100000000)), False)
``````

### “理解”风格：

``````next((i for i in range(100000000) if i == 1000), False)
``````

Oneliner：

``````thefirst = [i for i in range(10) if i > 3][0]
``````

### Tags

python   iterator