Explicit is better than implicit(明了胜于晦涩),就是说那种方式更清晰就用哪一种方式,不要盲目的都使用表达式。
1. 列表推导式:
例一:
multiples = [i for i in range(30) if i % 3 is 0] print(multiples) # Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
def squared(x): return x*x multiples = [squared(i) for i in range(30) if i % 3 is 0] print multiples # Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
2. lambda表达式:
add = lambda x, y : x+y
add(1,2) # 结果为3
def get_y(a,b):
return lambda x:ax+b
y1 = get_y(1,1)
y1(1) # 结果为2
# 需求:将列表中的元素按照绝对值大小进行升序排列
list1 = [3,5,-4,-1,0,-2,-6]
sorted(list1, key=lambda x: abs(x))
当然,也可以如下:
list1 = [3,5,-4,-1,0,-2,-6]
def get_abs(x):
return abs(x)
sorted(list1,key=get_abs)
只不过这种方式的代码看起来不够Pythonic
3. ?表达式
(1) variable = a if exper else b
(2) variable = (exper and [b] or [c])[0]
(3) variable = exper and b or c
上面三种用法都可以达到目的,类似C语言中 variable = exper ? b : c;即:如果exper表达式的值为true则variable = b,否则,variable = c
例如:
a, b = 1, 2 max = a if a > b else b max2 = (a > b and [a] or [b])[0] # list max3 = a > b and a or b print max,max2,max3
4. sorted
list1 = [3,5,-4,-1,0,-2,-6] def get_abs(x): return abs(x) a=sorted(list1,key=get_abs) print list1,a
dica = {"a":2,"c":8,"d":6} dicb = sorted(dica.items(),key=lambda x:x[0]) print dicb print sorted(dica.keys())