Python 返回符合条件的列表子集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35101426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return a subset of list that matches condition
提问by Will
Let's say I have a list of int
s:
假设我有一个int
s列表:
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)
What's a Pythonic way to return a sub-list
of element in a list
for which meetsCondition(element)
is True
?
list
在list
for which meetsCondition(element)
is 中返回元素的子元素的 Pythonic 方法是True
什么?
A naive approach:
一种幼稚的方法:
def subList(inputList):
outputList = []
for element in inputList:
if meetsCondition(element):
outputList.append(element)
return outputList
divisibleBySeven = subList(listOfNumbers)
Is there a simple way to do this, perhaps with a list comprehension or set()
functions, and without the temporary outputList
?
有没有一种简单的方法可以做到这一点,也许使用列表理解或set()
函数,而没有临时的outputList
?
采纳答案by thefourtheye
Use list comprehension,
使用列表理解,
divisibleBySeven = [num for num in inputList if num != 0 and num % 7 == 0]
or you can use the meetsCondition
also,
或者你也可以使用meetsCondition
,
divisibleBySeven = [num for num in inputList if meetsCondition(num)]
you can actually write the same condition with Python's truthysemantics, like this
您实际上可以使用 Python 的真实语义编写相同的条件,如下所示
divisibleBySeven = [num for num in inputList if num and num % 7]
alternatively, you can use filter
function with your meetsCondition
, like this
或者,您可以将filter
function 与您的 一起使用meetsCondition
,就像这样
divisibleBySeven = filter(meetsCondition, inputList)