加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python过滤函数 – 单个结果

发布时间:2020-12-20 11:42:10 所属栏目:Python 来源:网络整理
导读:参见英文答案 find first sequence item that matches a criterion ????????????????????????????????????2个 在Python中是否有一个内置函数,它将返回给定列表和验证函数的单个结果? 例如,我知道我可以做以下事情: resource = list(filter(lambda x: x.uri
参见英文答案 > find first sequence item that matches a criterion ????????????????????????????????????2个
在Python中是否有一个内置函数,它将返回给定列表和验证函数的单个结果?

例如,我知道我可以做以下事情:

resource = list(filter(lambda x: x.uri == uri,subject.resources))[0]

以上将基于ther resource.uri字段从资源列表中提取资源.虽然这个字段值是uinique,但我知道我要么有1个或0个结果. filter函数将迭代整个列表.在我的情况下它的20个元素,但我想知道是否有一些其他内置方法来停止第一次匹配的迭代.

解决方法

见 https://docs.python.org/3/library/functions.html#next

next(iterator[,default])

Retrieve the next item from the iterator by calling its next() method. If default is given,it is returned if the iterator is exhausted,otherwise StopIteration is raised.

例如在你的情况下:

resource = next(filter(lambda x: x.uri == uri,subject.resources),None)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读