按谓词过滤 Python 列表 [英] Filter a Python list by predicate

查看:36
本文介绍了按谓词过滤 Python 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情:

<预><代码>>>>lst = [1, 2, 3, 4, 5]>>>lst.find(lambda x: x % 2 == 0)2>>>lst.findall(lambda x: x % 2 == 0)[2, 4]

在 Python 的标准库中是否有类似这样的行为?

我知道在这里自己动手很容易,但我正在寻找一种更标准的方法.

解决方案

可以使用过滤方式:

<预><代码>>>>lst = [1, 2, 3, 4, 5]>>>过滤器(lambda x:x % 2 == 0,lst)[2, 4]

或列表推导式:

<预><代码>>>>lst = [1, 2, 3, 4, 5]>>>[x for x in lst if x %2 == 0][2, 4]

要查找单个元素,您可以尝试:

<预><代码>>>>next(x for x in lst if x % 2 == 0)2

虽然如果没有匹配项会抛出异常,所以您可能希望将其包装在 try/catch 中.() 括号使其成为生成器表达式而不是列表推导式.

就我个人而言,虽然我只是使用常规过滤器/理解并采用第一个元素(如果有的话).

如果什么都没有找到,这些会引发异常

filter(lambda x: x % 2 == 0, lst)[0][x for x in lst if x %2 == 0][0]

这些返回空列表

filter(lambda x: x % 2 == 0, lst)[:1][x for x in lst if x %2 == 0][:1]

I would want to do something like:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.find(lambda x: x % 2 == 0)
2
>>> lst.findall(lambda x: x % 2 == 0)
[2, 4]

Is there anything nearing such behavior in Python's standard libraries?

I know it's very easy to roll-your-own here, but I'm looking for a more standard way.

解决方案

You can use the filter method:

>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda x: x % 2 == 0, lst)
[2, 4]

or a list comprehension:

>>> lst = [1, 2, 3, 4, 5]
>>> [x for x in lst if x %2 == 0]
[2, 4]

to find a single element, you could try:

>>> next(x for x in lst if x % 2 == 0)
2

Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch. The () brackets make this a generator expression rather than a list comprehension.

Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).

These raise an exception if nothing is found

filter(lambda x: x % 2 == 0, lst)[0]
[x for x in lst if x %2 == 0][0]

These return empty lists

filter(lambda x: x % 2 == 0, lst)[:1]
[x for x in lst if x %2 == 0][:1]

这篇关于按谓词过滤 Python 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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