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)