用于_操作
def for_loop(l, target):
for i in l:
if i == target:
return i
return None
l = [1, 2, 3, 4, 5]
print(for_loop(l, 0))
print(for_loop(l, 1))
# None
# 1
next
def _next(l, target):
return next((i for i in l if i == target), None)
l = [1, 2, 3, 4, 5]
print(_next(l, 0))
print(_next(l, 1))
# None
# 1
更多工具
more_itertools.first_true(可迭代,默认值=无,pred=无)
安装
pip install more-itertools
或直接使用
def first_true(iterable, default=None, pred=None):
return next(filter(pred, iterable), default)
from more_itertools import first_true
l = [1, 2, 3, 4, 5]
print(first_true(l, pred=lambda x: x == 0))
print(first_true(l, pred=lambda x: x == 1))
# None
# 1
比较
method |
time/s |
for_loop |
2.77 |
next() |
3.64 |
more_itertools.first_true() |
3.82 or 10.86 |
import timeit
import more_itertools
def for_loop():
for i in range(10000000):
if i == 9999999:
return i
return None
def _next():
return next((i for i in range(10000000) if i == 9999999), None)
def first_true():
return more_itertools.first_true(range(10000000), pred=lambda x: x == 9999999)
def first_true_2():
return more_itertools.first_true((i for i in range(10000000) if i == 9999999))
print(timeit.timeit(for_loop, number=10))
print(timeit.timeit(_next, number=10))
print(timeit.timeit(first_true, number=10))
print(timeit.timeit(first_true_2, number=10))
# 2.7730861
# 3.6409407000000003
# 10.869996399999998
# 3.8214487000000013