Python一行代码取出列表中符合条件的元素
程序员文章站
2022-07-12 14:51:41
...
问题描述
Python一行代码找出列表中符合条件的元素
解决方案
循环
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
安装
pip install more-itertools
或不安装
def first_true(iterable, default=None, pred=None):
return next(filter(pred, iterable), default)
调用 more_itertools.first_true(iterable, default=None, pred=None)
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
对比
方法 | 耗时/s |
---|---|
循环 | 2.81 |
next() | 2.85 |
more_itertools.first_true() | 10.58 |
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)
print(timeit.timeit(for_loop, number=10))
print(timeit.timeit(_next, number=10))
print(timeit.timeit(first_true, number=10))
# 2.8123628000000003
# 2.851581
# 10.5818328