
在该程序中,您将学习使用Python匿名函数显示整数2的幂。
要理解此示例,您应该了解以下Python编程主题:
在下面的程序中,我们在map()内置函数内部使用了一个匿名(lambda)函数来查找2的幂。
源代码
#使用匿名函数显示2的幂
terms = 10
# 以下取消注释代码以接受用户输入
# terms = int(input("有多少项? "))
# 使用匿名函数
result = list(map(lambda x: 2 ** x, range(terms)))
print("总项数:",terms)
for i in range(terms):
   print("2的",i,"次方等于",result[i])输出结果
总项数: 10 2的 0 次方等于 1 2的 1 次方等于 2 2的 2 次方等于 4 2的 3 次方等于 8 2的 4 次方等于 16 2的 5 次方等于 32 2的 6 次方等于 64 2的 7 次方等于 128 2的 8 次方等于 256 2的 9 次方等于 512
注意:要测试不同数量的项,请更改terms变量的值。
