返回匹配条件的列表的子集 [英] Return a subset of list that matches condition
问题描述
假设我有一个int
的列表:
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)
在meetsCondition(element)
是True
的list
中返回元素的子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的 truthy 这样的语义
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]
或者,您可以将filter
函数与meetsCondition
一起使用,
alternatively, you can use filter
function with your meetsCondition
, like this
divisibleBySeven = filter(meetsCondition, inputList)
这篇关于返回匹配条件的列表的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!