Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

python - 如果/否则列表理解?(if/else in a list comprehension?)

How can I do the following in Python?

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

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

Essentially:

(实质上:)

  1. replace all the Nones with empty strings, and then

    (用空字符串替换所有的None,然后)

  2. carry out a function.

    (执行功能。)

  ask by AP257 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can totally do that, it's just an ordering issue:

(您可以完全做到这一点,这只是订购问题:)

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

In general,

(一般来说,)

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

And, for list comprehensions with if conditions only,

(而且,与列表内涵if只是条件,)

[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.

(请注意,这实际上使用了一种不同的语言构造,即条件表达式 ,它本身不是理解语法的一部分,而for…in之后的if是列表理解的一部分,用于从可迭代的源中筛选元素。)


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...