📜  在Python使用匿名函数的打印能力

📅  最后修改于: 2021-04-23 17:10:39             🧑  作者: Mango

先决条件:匿名函数

在下面的节目中,我们使用的地图()内置函数找到2.在Python的权力内部的匿名(lambda)函数,匿名函数是没有名字的定义。
虽然使用def关键字定义了普通函数,但在Python中,使用lambda关键字定义了匿名函数。因此,匿名函数也称为lambda函数。
句法:

lambda arguments: expression

Lambda函数可以具有任意数量的参数,但只能有一个表达式。表达式被求值并返回
例子:

Input : ('The total terms is:', 10)

Output :
('2 raised to power', 0, 'is', 1)
('2 raised to power', 1, 'is', 2)
('2 raised to power', 2, 'is', 4)
('2 raised to power', 3, 'is', 8)
('2 raised to power', 4, 'is', 16)
('2 raised to power', 5, 'is', 32)
('2 raised to power', 6, 'is', 64)
('2 raised to power', 7, 'is', 128)
('2 raised to power', 8, 'is', 256)
('2 raised to power', 9, 'is', 512)
# Python Program to display the powers 
# of 2 using anonymous function
  
# Change this value for a different result
terms = 10
  
# Uncomment to take number of terms from user
# terms = int(input("How many terms? "))
  
# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))
  
# display the result
print("The total terms is:", terms)
for i in range(terms):
   print("2 raised to power", i, "is", result[i])

输出:

('The total terms is:', 10)
('2 raised to power', 0, 'is', 1)
('2 raised to power', 1, 'is', 2)
('2 raised to power', 2, 'is', 4)
('2 raised to power', 3, 'is', 8)
('2 raised to power', 4, 'is', 16)
('2 raised to power', 5, 'is', 32)
('2 raised to power', 6, 'is', 64)
('2 raised to power', 7, 'is', 128)
('2 raised to power', 8, 'is', 256)
('2 raised to power', 9, 'is', 512)