1、列表解析、lambda 匿名函数
value = [lambda: x + 100 for x in range(10)]
print(value[0])
print(value[0]())
>>:
<function <listcomp>.<lambda> at 0x0000021FBB52D9D8>
109
# 扩展
def multipliters():
"""
for i in range(4): 循环4次,最终i=3
:return:[lambda x: i * x, lambda x: i * x, lambda x: i * x, lambda x: i * x]
"""
return [lambda x: i * x for i in range(4)]
print([m(2) for m in multipliters()])
>>:
[6, 6, 6, 6]
2、函数默认参数
默认参数为可变类型:
def bar(lt1,lt2 = []):
lt2.append(lt1)
return lt2
l1 = bar(1,[3,4])
print(id(l1),l1)
l2 = bar(1)
print(id(l2),l2)
l3 = bar(2,[3,4])
print(id(l1),l3)
l4 = bar(2)
print(id(l4),l4)
>>:
2542419966728 [3, 4, 1]
2542419946120 [1]
2542419966728 [3, 4, 2]
2542419946120 [1, 2]
默认参数为不可变类型:
def foo(tp1,tp2=()): return tp1+tp2 t1 = foo((1,),(3,4)) print(id(t1),t1) t2 = foo((1,)) print(id(t2),t2) t3 = foo((2,),(3,4,5)) print(id(t3),t3) t4 = foo((2,)) print(id(t4),t4) ''' 2874698184384 (1, 3, 4) 2874698241584 (1,) 2874698161992 (2, 3, 4, 5) 2874698241528 (2,) '''