结合 FOR 循环和 IF 语句的 Pythonic 方式 [英] Pythonic way to combine FOR loop and IF statement

查看:35
本文介绍了结合 FOR 循环和 IF 语句的 Pythonic 方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在单独的行中同时使用 for 循环和 if 语句,例如:

<预><代码>>>>a = [2,3,4,5,6,7,8,9,0]... xyz = [0,12,4,6,242,7,9]... 对于 xyz 中的 x:...如果 x 在 a:... 打印(x)0,4,6,7,9

而且我知道当语句很简单时,我可以使用列表理解来组合这些,例如:

print([x for x in xyz if x in a])

但是我在任何地方都找不到一个很好的例子(可以复制和学习),演示一组复杂的命令(不仅仅是打印 x"),这些命令是在 for 循环和一些 if 语句的组合之后出现的.我期望的东西看起来像:

for x in xyz 如果 x 不在 a 中:打印(x...)

这难道不是python应该工作的方式吗?

解决方案

您可以使用 generator像这样的表达:

gen = (x for x in xyz if x not in a)对于 gen 中的 x:打印(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)

这篇关于结合 FOR 循环和 IF 语句的 Pythonic 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆