如何在列表中找到匹配条件的第一个元素?
假设我有一个列表,l,其中包含[5, 10, 15, 16, 20]. 我想获得所有可被5(前三个元素)整除的第一个元素,而不是最后一个20. 我该怎么做呢?我弄完了:
done = False
i = 0
while not done and i < len(l):
if l[i] % 5 == 0:
answer.append(source[i])
else:
done = True
i += 1
然而,这似乎效率低下。有没有更好的方法来做到这一点?
回答
该itertools.takewhile功能似乎是您想要的:
from itertools import takewhile
list(takewhile(lambda x: x % 5 == 0, [5, 10, 15, 16, 20]))
这返回[5, 10, 15].