lambda
表达式是一行函数。
它们在其他语言中也被称为匿名函数。如果你不想在程序中对一个函数使用两次,你也许会想用lambda表达式,它们和普通的函数完全一样。
原型
lambda 参数:操作(参数)
例子
add = lambda x, y : x + y
print(add(3, 5))
# Output: 8
这还有一些lambda表达式的应用案例,可以在一些特殊情况下使用:
列表排序
a = [(1, 2), (4, 1), (9, 10), (13, -3)]
a.sort(key=lambda x: x[1])
print(a)
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
列表并行排序
data = zip(list1, list2)
data = sorted(data)
list1, list2 = map(lambda t: list(t), zip(*data))
#build-in 自带函数
map(function, sequence)
map(str, range(1:12))
>>>['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
>>>list(map(lambda x: x*x, [2,3,4]))
>>>[4, 9, 16]
我们加了 list 转换,是为了兼容 Python3,在 Python2 中 map 直接返回列表,Python3 中返回迭代器。
filter(function, sequnce)
>>>list(filter(lambda x: x%2==0, [2,3,4]))
>>>[2,4]
!!! Removed from Python3 by default
The reduce
function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools
module, so you can do: from functools import reduce
使用reduce的函数仅且包含2个变量
reduce(function, sequence[, initial])
解释:先将 sequence 的前两个 item 传给 function,即 function(item1, item2),函数的返回值和 sequence 的下一个 item 再传给 function,即 function(function(item1, item2), item3),如此迭代,直到 sequence 没有元素,如果有 initial,则作为初始值调用。
也就是说:
reduece(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> reduce(lambda x,y:x+y,[1,3,5],10)
>>> 19
>>> reduce(lambda x,y:x+2,[1,0,1,0])
>>> 7 # [1,0,1,0]=>[3,1,0]=>[5,0]
>>> f = lambda a, b: a if (a > b) else b # 两两比较,取最大值
>>> reduce(f, [5, 8, 1, 10])
10
Iter()
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>>
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
>>>
>>> print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>>
>>> print reduce(lambda x, y: x + y, foo)
139
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
... print i, element
0 one
1 two
2 three
max(), min()
Eval带计算
evaluate = input(“Enter what operation x has to perform: “)
print(evaluate)
print(type(evaluate))
--------------------------------------------------------------------
Enter what operation x has to perform: x + x + 100 - 35 + 5 * 80
x + x + 100 - 35 + 5 * 80
<class 'str'>x = 10
print(type(x))
--------------------------------------------------------------------<class 'int'>expression = eval(evaluate)
print(expression)
print(type(expression))
--------------------------------------------------------------------
485
<class 'int'>