查找第一个匹配条件的序列项 [英] Find first sequence item that matches a criterion
问题描述
查找/返回符合特定条件的第一个列表项的最优雅、最有效的方法是什么?
What would be the most elegant and efficient way of finding/returning the first list item that matches a certain criterion?
例如,如果我有一个对象列表,我想获取那些具有 obj.val==5
属性的对象中的第一个对象.我当然可以使用列表理解,但这会导致 O(n),如果 n 很大,那就太浪费了.一旦满足条件,我也可以使用带有 break
的循环,但我认为可能有更pythonic/优雅的解决方案.
For example, if I have a list of objects and I would like to get the first object of those with attribute obj.val==5
. I could of course use list comprehension, but that would incur O(n) and if n is large, it's wasteful. I could also use a loop with break
once the criterion was met, but I thought there could be a more pythonic/elegant solution.
推荐答案
如果你的对象没有任何其他索引或排序信息,那么你将不得不迭代直到找到这样的对象:
If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
然而,这比完整的列表理解要快.比较这两个:
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
第一个需要 5.75ms,第二个需要 58.3µs(快 100 倍,因为循环短了 100 倍).
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
这篇关于查找第一个匹配条件的序列项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!