Tim Wong
深思心思
Published in
2 min readOct 23, 2019

--

【Py11】one line if then else

日期: 2019-Oct-05, 作者: Tim Wong

one line if then else 很多programming language 都有,當然包括Python。

不過要注意,當連著for-loop 一起用只有if 跟 if+else 是有些syntax 上的分的。

先看one-line 中只有if-else 的例子:

a = [1,2,3,4,5,6,7]result = []
for i in a:
result.append(i*2 if i%2==0 else i*3)

print(result)
-------------------------
[3, 4, 9, 8, 15, 12, 21]

Syntax 是:

(result if ‘yes’) if (expression) else (result if ‘no’)

如果one-line 只有 for-loop 是這樣的:

b = [i for i in a]
print(b)
---------------------
[1, 2, 3, 4, 5, 6, 7]

注意!!

c = [i*2 for i in a if i%2==0]
print(c)
-------------------------------
[4, 8, 12]
d = [i*2 if i%2==0 else i*3 for i in a]
print(d)
-------------------------------
[3, 4, 9, 8, 15, 12, 21]

即是,有以下的syntax 差別:

(result if ‘yes’) for (for-expression) if (expression)

(result if ‘yes’) if (expression) else (result if ‘no’) for (for-expression)

以for (for-expression) 為中心的話,只有if 時,if (expression)放後面; 但if-else 都有時,if (expression) + else (result if ‘no’) 一起放在前面。

是不是有些怪?

全力衝刺中的一團火

我是阿Tim | timwong.ai@gmail.com

--

--