如果/否则列表理解 [英] if/else in a list comprehension

查看:62
本文介绍了如果/否则列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中执行以下操作?

How can I do the following in Python?

row = [unicode(x.strip()) for x in row if x is not None else '']

本质上:

  1. 用空字符串替换所有None,然后
  2. 执行功能.

推荐答案

您完全可以做到这一点.这只是一个订购问题:

You can totally do that. It's just an ordering issue:

[unicode(x.strip()) if x is not None else '' for x in row]

通常

[f(x) if condition else g(x) for x in sequence]

而且,仅对于具有if条件的列表理解,

And, for list comprehensions with if conditions only,

[f(x) for x in sequence if condition]

请注意,这实际上使用了另一种语言构造,即条件表达式,它本身不属于

Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after the for…in is part of list comprehensions and used to filter elements from the source iterable.

条件表达式可以在各种情况下使用,您需要根据某些条件在两个表达式值之间进行选择.这与其他语言中存在的三元运算符?: .例如:

Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator ?: that exists in other languages. For example:

value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')

这篇关于如果/否则列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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