lambda和正则表达式

2019-04-22  本文已影响0人  脏脏包盛

lambda表达式

g=lambda x:x+1

输出结果

g(1)
>>>2
g(2)
>>>3

相当于匿名函数,x为入口参数,x+1为函数体,用函数来表示为:

def g(x):
    return x+1

Python中,也有几个定义好的全局函数方便使用的,filter, map, reduce

map函数

map() function returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)

map(fun, iter) 

前一个参数为函数,后一个为iterable
sample

numbers1 = [1, 2, 3] 
numbers2 = [4, 5, 6] 
result = map(lambda x, y : x + y, numbers1, numbers2)
print(list(result))

output:[5, 7, 9]

# List of strings 
l = ['sat', 'bat', 'cat', 'mat'] 
  
# map() can listify the list of strings individually 
test = list(map(list, l)) 
print(test) 

outputs:

[['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
上一篇 下一篇

猜你喜欢

热点阅读