01-20 96—100
______egon新书python全套来袭请看:https://egonlin.com/book.html
96、选择输出结果
def doff(arg1, *args):
print(type(args))
doff("applea", "bananas", "cherry")
A.str
B.int
C.tuple
D.list
E.dict
# 答案:
C
97、下面程序的输出结果是
d = lambda p:p*2
t = lambda p:p*3
x = 2
x = d(x)
x = t(x)
x = d(x)
print(x)
# 答案
24
98、以下代码输出是什么,请给出答案并解释
def multipliers():
return [lambda x:x*i for i in range(4)]
print([m(2) for m in multipliers()])
# 答案:
[6,6,6,6]
闭包函数延迟绑定问题。
# 请修改 multipliers 的定义来产生期望的结果
def multipliers():
return [lambda x, i=i:x*i for i in range(4)]
print([m(2) for m in multipliers()])
99、写函数
'''
有一个数据结构如下所示,请编写⼀个函数从该结构数据中返回由指定的字段和对应的值组成的字典。如果指定字段不存在,则跳过该字段。
'''
data:{
"time":"2016-08-05T13:13:05",
"some_id":"ID1234",
"grp1":{"fld1":1, "fld2":2,},
"xxx2":{"fld3":0, "fld4":0.4,},
"fld6":11,
"fld7": 7,
"fld46":8
}
# fields:由"|"连接的以 fld 开头的字符串, 如 fld2|fld7|fld29
# 答案一:
def select(data, fields):
result = {}
field_lst = fields.split('|')
for key in data:
if key in field_lst:
result[key] = data[key]
elif type(data[key]) == dict:
res = select(data[key], fields)
result.update(res)
return result
data = {"time": "2016-08-05T13:13:05",
"some_id": "ID1234",
"grp1": {"fld1": 1, "fld2": 2},
"xxx2": {"fld3": 0, "fld5": 0.4},
"fld6": 11,
"fld7": 7,
"fld46": 8}
fields = 'fld2|fld3|fld7|fld19'
print(select(data, fields))
# 答案二:
def select(data,fields,result = {}):
field_lst = fields.split('|')
for key in data:
if key in field_lst:
result[key] = data[key]
elif type(data[key]) == dict:
select(data[key], fields)
return result
data={"time":"2016-08-05T13:13:05",
"some_id":"ID1234",
"grp1":{ "fld1":1,"fld2":2},
"xxx2":{ "fld3":0,"fld5":0.4},
"fld6":11,
"fld7":7,
"fld46":8}
fields = 'fld2|fld3|fld7|fld19'
select(data,fields)
print(select(data,fields))
100、谈谈你对闭包的理解?
闭包(closure)是函数式编程的重要的语法结构。闭包也是一种组织代码的结构,它同样提高了代码的可重复使用性。
当一个内嵌函数引用其外部作作用域的变量,我们就会得到一个闭包. 总结一下,创建一个闭包必须满足以下几点:
- 必须有一个内嵌函数
- 内嵌函数必须引用外部函数中的变量
- 外部函数的返回值必须是内嵌函数