Python⼀⾏代码取出列表中符合条件的元素⽂章⽬录
问题描述
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)
调⽤
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
参考⽂献
1.
2.