Python中的条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12986996/
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
Conditional for in Python
提问by Alan Coromano
Does Python have something like below?
Python 有类似下面的东西吗?
for item in items #where item>3:
#.....
I mean Python 2.7 and Python 3.3 both together.
我的意思是同时使用 Python 2.7 和 Python 3.3。
采纳答案by georg
You can combine the loop with a generator expression:
您可以将循环与生成器表达式结合使用:
for x in (y for y in items if y > 10):
....
itertools.ifilter(py2) / filter(py3) is another option:
itertools.ifilter(py2) / filter(py3) 是另一种选择:
items = [1,2,3,4,5,6,7,8]
odd = lambda x: x % 2 > 0
for x in filter(odd, items):
print(x)
回答by Rohit Jain
You mean something like this: -
你的意思是这样的: -
item_list = [item for item in items if item > 3]
Or, you can use Generatorexpression, that will not create a new list, rather returns a generator, which then returns the next element on each iteration using yieldmethod: -
或者,您可以使用Generator表达式,它不会创建新列表,而是返回一个生成器,然后使用yield方法返回每次迭代的下一个元素:-
for item in (item for item in items if item > 3):
# Do your task
回答by Mark Amery
There isn't a special syntax like the wherein your question, but you could always just use an ifstatement within your forloop, like you would in any other language:
没有像where您的问题中的特殊语法,但您始终可以if在for循环中使用语句,就像在任何其他语言中一样:
for item in items:
if item > 3:
# Your logic here
or a guard clause (again, like any other language):
或保护条款(同样,像任何其他语言一样):
for item in items:
if not (item > 3): continue
# Your logic here
Both of these boring approaches are almost as succinct and readable as a special syntax for this would be.
这两种无聊的方法几乎都像一个特殊的语法一样简洁易读。
回答by jfs
You could use an explicit ifstatement:
您可以使用显式if语句:
for item in items:
if item > 3:
# ...
Or you could create a generator if you need a name to iterate later, example:
或者,如果您需要稍后迭代的名称,您可以创建一个生成器,例如:
filtered_items = (n for n in items if n > 3)
Or you could pass it to a function:
或者你可以将它传递给一个函数:
total = sum(n for n in items if n > 3)
It might be matter of taste but I find a for-loop combined with inlined genexpr such as for x in (y for y in items if y > 3):to be ugly compared to the above options.
这可能是品味问题,但我发现一个 for 循环与内联的基因表达式相结合,例如for x in (y for y in items if y > 3):与上述选项相比很难看。
回答by Sergiy Kolodyazhnyy
Python 3 and Python 2.7 both have filter()function which allows extracting items out of a list for which a function (in the example below, that's lambda function) returns True:
Python 3 和 Python 2.7 都具有filter()允许从函数(在下面的示例中,这是 lambda 函数)返回的列表中提取项目的函数True:
>>> nums=[1,2,3,4,5,6,7,8]
>>> for item in filter(lambda x: x>5,nums):
... print(item)
...
6
7
8
Omitting function in filter()will extract only items that are True, as stated in pydoc filter
省略函数 infilter()将仅提取 是 的项目True,如中所述pydoc filter

