如何返回与条件匹配的列表的子集 [英] How to return a subset of a list that matches a condition

查看:35
本文介绍了如何返回与条件匹配的列表的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 int s的列表:

Let's say I have a list of ints:

listOfNumbers = range(100)

我想返回一个满足一定条件的元素的列表,说:

And I want to return a list of the elements that meet a certain condition, say:

def meetsCondition(element):
    return bool(element != 0 and element % 7 == 0)

list 中为其返回 meetsCondition(element) True的元素的子 list 的Python方法是什么??

What's a Pythonic way to return a sub-list of element in a list for which meetsCondition(element) is True?

幼稚的方法:

def subList(inputList):
    outputList = []

    for element in inputList:
        if meetsCondition(element):
            outputList.append(element)

    return outputList

divisibleBySeven = subList(listOfNumbers)

是否有一种简单的方法来执行此操作,也许具有列表理解功能或 set()函数,并且没有临时的 outputList ?

Is there a simple way to do this, perhaps with a list comprehension or set() functions, and without the temporary outputList?

推荐答案

使用列表理解,

divisibleBySeven = [num for num in inputList if num != 0 and num % 7 == 0]

或者您也可以使用 meetsCondition

divisibleBySeven = [num for num in inputList if meetsCondition(num)]

您实际上可以使用Python的真实的语义,例如

you can actually write the same condition with Python's truthy semantics, like this

divisibleBySeven = [num for num in inputList if num and num % 7]


或者,您可以在 meetsCondition 中使用 filter 函数,如下所示

divisibleBySeven = filter(meetsCondition, inputList)

%timeit

listOfNumbers = range(1000000)

%timeit [num for num in listOfNumbers if meetsCondition(num)]
[out]:
243 ms ± 4.51 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit list(filter(meetsCondition, listOfNumbers))
[out]:
211 ms ± 4.19 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

这篇关于如何返回与条件匹配的列表的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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