1.下面这段代码的输出结果是什么,并给出你的解释
def index():
return [lambda x : i * x for i in range(4)]
print([m(2) for m in index()])
[lambda x: i*x for i in range(5)]
运行结果:
#生成了一个包含5个匿名函数的列表
[<function <listcomp>.<lambda> at 0x0000000004882158>,
<function <listcomp>.<lambda> at 0x00000000048821E0>,
<function <listcomp>.<lambda> at 0x0000000004882378>,
<function <listcomp>.<lambda> at 0x0000000004882400>,
<function <listcomp>.<lambda> at 0x0000000004882488>]
def create_multipliers():
return [lambda x: i*x for i in range(5)]
for multiplier in create_multipliers():
print(multiplier(2))
运行结果:
8
8
8
8
8
由于Python的迟绑定(late binding)机制,闭包中内部函数的值只有在被调用时才会进行查询,因此create_multipliers函数返回的lambda函数被调用时,会在附近的作用域中查询变量i的值,而在create_multipliers生成返回数组之后,整数i的值是4,不会再改变,因此返回数组中每个匿名函数实际上都是:
lambda x: 4*x
解决办法是将临时值也保存在匿名函数的作用域内,在声明匿名函数时就查询变量的值:
def create_multipliers():
return [lambda x,i=i: i*x for i in range(5)]
for multiplier in create_multipliers():
print(multiplier(2))
运行结果:
0
2
4
6
8
2.有一个列表[3,4,1,2,5,6,6,5,4,3,3]请写出一个函数,找出该列表中没有重复的数的总和
方法1
l1 = [3,4,1,2,5,6,6,5,4,3,3]
l2 = []
for i in l1:
if i not in l2:
l2.append(i)
x = 0
for j in l2:
x += j
print(j)
方法2
l1 = [3,4,1,2,5,6,6,5,4,3,3]
x = 0
s1 = set(l1)
for i in s1:
x += i
print(x)
3.什么是函数的递归调用?书写递归函数需要注意什么?你能否利用递归函数打印出下面列表中每一个元素(只能打印数字),l = [1,[2,[3,[4,[5,[6,[7,[8,[9]]]]]]]]]
l = [1,[2,[3,[4,[5,[6,[7,[8,[9]]]]]]]]]
def abc(li):
for i in li:
if type(i) != list:
print(i)
else:
abc(i)
abc(l)