python序列查找功能 [英] python sequence find function

查看:200
本文介绍了python序列查找功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何找到一个满足特定标准的序列中的对象?
列表理解和过滤遍历整个列表。
是手工制作的唯一选择吗?

  mylist = [10,2,20,5,50] 
find(mylist,lambda x:x> 10)#返回20


解决方案

  mylist = [10,2,20,5,50] 
found = next(i for my in mylist如果谓词(i))

或者,在Python 2.4 / 2.5和下一个()是不是一个内置的:

  found =(我为mylist if谓词(i))。next()

请注意 next / code>如果找不到任何元素,则引发 StopIteration 。在大多数情况下,这可能是好的,你要求第一个元素,不存在这样的元素,所以程序可能无法继续。



另一方面,你知道该怎么做,你可以提供一个默认的 next():

  conf_files = ['〜/ .foorc','/ etc / foorc'] 
conf_file = next((f用于conf_files中的f if os.path。存在(f)),
'/usr/lib/share/foo.defaults')


How do I find an object in a sequence satisfying a particular criterion? List comprehension and filter go through the entire list. Is the only alternative a handmade loop ?

mylist = [10, 2, 20, 5, 50]
find(mylist, lambda x:x>10) # returns 20

解决方案

here's the pattern I use:

mylist = [10, 2, 20, 5, 50]
found = next(i for i in mylist if predicate(i))

Or, in python 2.4/2.5 and , next() is a not a builtin:

found = (i for i in mylist if predicate(i)).next()

Do note that next() raises StopIteration if no element was found. In most cases, that's probably good, you asked for the first element, no such element exists, and so the program probably cannot continue.

If, on the other hand, you do know what to do in that case, you can supply a default to next():

conf_files = ['~/.foorc', '/etc/foorc']
conf_file = next((f for f in conf_files if os.path.exists(f)),
                 '/usr/lib/share/foo.defaults')

这篇关于python序列查找功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆