Pythonic方式结合FOR循环和IF语句 [英] Pythonic way to combine FOR loop and IF statement
问题描述
>>>我知道如何在循环和if语句中使用单独的行; a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
...在xyz中为x:
...如果x在a中:
... print(x)
0,4,6,7,9
我知道当语句很简单时,我可以使用列表理解来组合这些语句,如:/ b
print([x for xyz if x in a])
但是我找不到任何地方的一个很好的例子(复制和学习),演示一组复杂的命令(不仅仅是print x),这些命令在for循环还有一些if语句。一些我期望的样子:
for x in xyz if x not in a:
print(x。 ..)
这不是python应该工作的方式吗?
解决方案您可以使用生成器表达式如下所示:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ x $ x $ x $ x $ x $ x $ x $ x $ x $ x
for x:
print x
I know how to use both for loops and if statements on separate lines, such as:
>>> a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
... for x in xyz:
... if x in a:
... print(x)
0,4,6,7,9
And I know I can use a list comprehension to combine these when the statements are simple, such as:
print([x for x in xyz if x in a])
But what I can't find is a good example anywhere (to copy and learn from) demonstrating a complex set of commands (not just "print x") that occur following a combination of a for loop and some if statements. Something that I would expect looks like:
for x in xyz if x not in a:
print(x...)
Is this just not the way python is supposed to work?
You can use generator expressions like this:
gen = (x for x in xyz if x not in a)
for x in gen:
print x
这篇关于Pythonic方式结合FOR循环和IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!