一定要会的新技术功能
快速交换(Quick swap)
# in python, also works in ES6
s1 = 3
s2 = 4
# Quick swap
s1, s2 = s2, s1
惰性计算(Lazy evaluation)
是指仅仅在真正需要执行的时候才计算表达式的值。
-
避免不必要的计算,带来性能的提升。
对于条件表达式if x and y,在x为false的情况下y表达式的值将不再计算。而对于if x or y,当x的值为true的时候将直接返回,不再计算y的值。因此编程中可以利用该特性:- 在
and逻辑中,将小概率发生的条件放在前面; - 在
or逻辑中,将大概率发生的时间放在前面,有助于性能的提升。
- 在
-
节省空间,使得无线循环的数据结构成为可能。
Python中最经典的使用延迟计算的例子就是生成式表达器了,它在每次需要计算的时候才通过yield产生所需要的元素。
例:斐波那契数列在Python中实现起来很容易,使用yied对于while True也不会导致其他语言中所遇到的无线循环问题。
def fib():
a,b = 0,1
while True:
yield a
a,b = b,a+b
fib_gen = fib()
for i in range(30):
print(fib_gen.next())
解构赋值(Destructuring assignment)
# In python
# Destruction
li = (1, 2, 3)
a, b, c = li
print(b)
li1 = [1, 2, 3, 4, 5, 6]
c, *_, d = li1
// In ES6
// we have an array with the name and surname
let arr = ["Ilya", "Kantor"]
// destructuring assignment
let [firstName, surname] = arr;
alert(firstName); // Ilya
alert(surname); // Kantor
Get details from site ES6 destructuring assignment.

浙公网安备 33010602011771号