Python Lambda, map, filter

lambda arguments: expression
  • This function can have any number of arguments but only one expression, which is evaluated and returned.
  • One is free to use lambda functions wherever function objects are required.
  • You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression.
  • It has various uses in particular fields of programming besides other types of expressions in functions.
# Example
def cube(y): 
    return y*y*y; 
  
g = lambda x: x*x*x 

print(g(7)) 
print(cube(5)) 

Using lambda with...

# filter() with lambda() 
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
final_list = list(filter(lambda x: (x%2 != 0) , li)) 
print(final_list) 

# map() with lambda()  
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61] 
final_list = list(map(lambda x: x*2 , li)) 
print(final_list) 

# reduce() with lambda() 
from functools import reduce
li = [5, 8, 10, 20, 50, 100] 
sum = reduce((lambda x, y: x + y), li) 
print (sum) 

Map

map(fun, iter)

def addition(n): 
    return n + n 
  
# We double all numbers using map() 
numbers = (1, 2, 3, 4) 
result = map(addition, numbers) 
print(list(result)) 

# Double all numbers using map and lambda 
numbers = (1, 2, 3, 4) 
result = map(lambda x: x + x, numbers) 
print(list(result)) 

# Add two lists using map and lambda 
numbers1 = [1, 2, 3] 
numbers2 = [4, 5, 6] 
result = map(lambda x, y: x + y, numbers1, numbers2) 
print(list(result))  # [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) 
# [['s', 'a', 't'], ['b', 'a', 't'], ['c', 'a', 't'], ['m', 'a', 't']]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,936评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,979评论 0 13
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,531评论 0 23
  • 早春四月,家乡小城还是春寒料峭,春的脚步迟迟疑疑。因为一个偶然的学习机会我来到了A城,一下火车迎面扑来的是暖融融的...
    黑龙江冷月阅读 636评论 2 3
  • 刚毕业的时候,踌躇着人生的方向,找了份自己相对而言感兴趣的工作,不紧不慢得当个职场人。好像还是那么笨手笨脚的职场人...
    于多萌阅读 183评论 0 2

友情链接更多精彩内容