一尘不染

如何返回与条件匹配的列表的子集?

python

假设我有一个ints的列表:

listOfNumbers = range(100)

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

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

listlistfor中 返回元素的子元素的Python方法meetsCondition(element)True什么?

天真的方法:

def subList(inputList):
    outputList = []

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

    return outputList

divisibleBySeven = subList(listOfNumbers)

有没有一种简单的方法可以执行此操作,也许具有列表理解或set()函数,而没有临时的outputList


阅读 248

收藏
2020-12-20

共1个答案

一尘不染

使用清单理解,

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

或者您可以使用meetsCondition也,

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

您实际上可以使用Python的真实语义编写相同的条件,例如

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

另外,您也可以使用filter功能与你的meetsCondition,像这样的

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)
2020-12-20