列表理解中的 if/else [英] if/else in a list comprehension

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

问题描述

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

How can I do the following in Python?

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

本质上:

  1. 用空字符串替换所有的无,然后
  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]

请注意,这实际上使用了不同的语言结构,即条件表达式,它本身不属于 推导式语法,而 for...in 之后的 if 是列表推导式的一部分,用于从源可迭代.

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')

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

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