python惯用python for循环if else语句 [英] python idiomatic python for loop if else statement

查看:1334
本文介绍了python惯用python for循环if else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在循环中使用惯用Python 中的 else 语句?没有 else 我可以编写例如:

  res = [i for i在[1,2,3,4,5]中,如果i < 4] 

结果是: [1,2,3]


$ b

上面代码的正常形式是:

  res = [] 
for i in [1,2,3,4,5]:
if i< 4:
res.append(i)

结果与习惯形式: [1,2,3]



我想要:

  res = [i for i in [1,2,3,4,5] if i< 4 else 0] 

我得到 SyntaxError:invalid syntax 。结果应该是: [1,2,3,0,0]
这是正常的代码:

  res = [] 
for i in [1,2,3,4,5]:
if i< 4:
res.append(i)
else:
res.append(0)

结果是: [1,2,3,0,0]

解决方案

您很接近,您只需要将三元组移动到您创建值的列表理解部分。

  res = [i if i< 4 else 0 for i in range(1,6)] 


How can I use else statement in an idiomatic Python for loop? Without else I can write e.g.:

res = [i for i in [1,2,3,4,5] if i < 4]

The result is: [1, 2, 3]

The normal form of the above code is:

res = []
for i in [1,2,3,4,5]:
    if i < 4:
        res.append(i)

The result is the same as in idiomatic form: [1, 2, 3]

And I want this:

res = [i for i in [1,2,3,4,5] if i < 4 else 0]

I get SyntaxError: invalid syntax. The result should be: [1, 2, 3, 0, 0] The normal code of this is:

res = []
for i in [1,2,3,4,5]:
    if i < 4:
        res.append(i)
    else:
        res.append(0)

The result is: [1, 2, 3, 0, 0]

解决方案

You were close, you just have to move the ternary to the part of the list comprehension where you're creating the value.

res = [i if i < 4 else 0 for i in range(1,6)] 

这篇关于python惯用python for循环if else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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