Python学习-lambda

1.lambda

用lambda写自定义方程。

#first way write function
def echo_word(word1, echo):
    """Concatenate echo copies of word1."""
    words = word1 * echo
    return words

#second way to write function
# Define echo_word as a lambda function: echo_word
echo_word = (lambda word1,echo:word1*echo)

#以上两种方法的效果都是一样的,都是创建一个echo_word的自定义方程
# Call echo_word: result
result = echo_word("hey",5)

# Print result
print(result)

输出结果如下:

<script.py> output:
    heyheyheyheyhey

2.Map() and lambda functions

在编程中,map() 函数用于对可迭代对象(如列表、元组等)中的每个元素应用一个函数,然后返回一个包含所有结果的迭代器(在Python 2中返回的是一个列表)。通过 list() 将其转换为列表并打印出来。

# Create a list of strings: spells
spells = ["protego", "accio", "expecto patronum", "legilimens"]

# Use map() to apply a lambda function over spells: shout_spells
shout_spells= map(lambda item:item+"!!!", spells)

# Convert shout_spells to a list: shout_spells_list
shout_spells_list=list(shout_spells)

# Print the result
print(shout_spells_list)

3.Filter() and lambda functions

filter函数可以过滤符合条件元素。map和filter返回的结果不同。

使用filter:
# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf']

# Use filter() to apply a lambda function over fellowship: result
result = filter(lambda member: len(member)>6,fellowship)

# Convert result to a list: result_list
result_list=list(result)

# Print result_list
print(result_list)

#输出结果:
<script.py> output:
    ['samwise', 'aragorn', 'boromir', 'legolas', 'gandalf']

使用map:
# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf']

# Use filter() to apply a lambda function over fellowship: result
result = map(lambda member: len(member)>6,fellowship)

# Convert result to a list: result_list
result_list=list(result)

# Print result_list
print(result_list)


map输出结果:
[False, True, False, False, True, True, True, False, True]

4.Reduce() and lambda functions

reduce() 函数是 Python 中的一个内置函数,位于 functools 模块中。它用于将一个函数累积地应用于一个可迭代对象的所有元素,从而将可迭代对象归约为单个值。

reduce() 函数的工作原理是,从可迭代对象的第一个元素开始,将累积值和当前元素传递给指定的函数,然后将函数的结果作为下一次迭代的累积值。这个过程会持续进行,直到遍历完可迭代对象中的所有元素,最终返回归约后的单个值。

# Import reduce from functools
from functools import reduce 

# Create a list of strings: stark
stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon']

# Use reduce() to apply a lambda function over stark: result
result = reduce(lambda item1,item2:item1+item2, stark)

# Print the result
print(result)

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值