第 3 章:控制流
if / for / while;推导式是 Python 味最浓的部分。
01if / elif / else
Python
x = 2
if x > 2:
print(">")
elif x == 2:
print("=")
else:
print("<")
Kotlin
val x = 2
when {
x > 2 -> println(">")
x == 2 -> println("=")
else -> println("<")
}
ArkTS
const x = 2;
if (x > 2) {
console.info(">");
} else if (x === 2) {
console.info("=");
} else {
console.info("<");
}
02for 遍历
Python 的 for 本质是「遍历可迭代对象」,没有 C 式三条件 for。
Python
for i in range(3):
print(i) # 0 1 2
for ch in "hi":
print(ch)
Kotlin
for (i in 0 until 3) {
println(i)
}
for (ch in "hi") {
println(ch)
}
ArkTS
for (let i = 0; i < 3; i++) {
console.info(i);
}
for (const ch of "hi") {
console.info(ch);
}
range(n) ≈ Kotlin 0 until n;要含尾用 range(a, b+1) 或记「右开」。03while / break / continue
Python
n = 3
while n > 0:
print(n)
n -= 1
if n == 1:
continue
if n == 0:
break
Kotlin
var n = 3
while (n > 0) {
println(n)
n--
}
ArkTS
let n = 3;
while (n > 0) {
console.info(n);
n--;
}
04列表推导式
把「map + filter」写成一行,读起来像集合生成式。
Python
nums = [1, 2, 3, 4]
evens = [x * 2 for x in nums if x % 2 == 0]
# [4, 8]
Kotlin
val nums = listOf(1, 2, 3, 4)
val evens = nums.filter { it % 2 == 0 }.map { it * 2 }
ArkTS
const nums = [1, 2, 3, 4];
const evens = nums.filter((x) => x % 2 === 0).map((x) => x * 2);
推导式别嵌太深;超过两层就改回普通 for,可读性优先。
05match(3.10+)≈ when
Python
cmd = "run"
match cmd:
case "run":
print("go")
case "stop":
print("halt")
case _:
print("other")
Kotlin
when (cmd) {
"run" -> println("go")
"stop" -> println("halt")
else -> println("other")
}
ArkTS
switch (cmd) {
case "run":
console.info("go");
break;
case "stop":
console.info("halt");
break;
default:
console.info("other");
}