假设我有一个ints的列表:
int
listOfNumbers = range(100)
我想返回满足一定条件的元素的列表,例如:
def meetsCondition(element): return bool(element != 0 and element % 7 == 0)
list在listfor中 返回元素的子元素的Python方法meetsCondition(element)是True什么?
list
meetsCondition(element)
True
天真的方法:
def subList(inputList): outputList = [] for element in inputList: if meetsCondition(element): outputList.append(element) return outputList divisibleBySeven = subList(listOfNumbers)
有没有一种简单的方法可以执行此操作,也许具有列表理解或set()函数,而没有临时的outputList?
set()
outputList
使用清单理解,
divisibleBySeven = [num for num in inputList if num != 0 and num % 7 == 0]
或者您可以使用meetsCondition也,
meetsCondition
divisibleBySeven = [num for num in inputList if meetsCondition(num)]
您实际上可以使用Python的真实语义编写相同的条件,例如
divisibleBySeven = [num for num in inputList if num and num % 7]
另外,您也可以使用filter功能与你的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)