问题描述
查找/返回符合特定条件的第一个列表项的最优雅,最有效的方法是什么?
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/elegant解决方案.
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.75毫秒,第二个需要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).
这篇关于查找符合条件的第一个序列项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!