刷题(七)

题目

请写出下列代码的运行结果

def f(str1, *args, **kwargs):
    print(str1, args, kwargs)


l = [1, 2, 3]
t = [4, 5, 6]
d = {"a": 7, "b": 8, "c": 9}

f(1, 2)   #1
f(1, 2, 3, "python")   #2
f("python", a=1, b=2, c=3)  #3
f("python", l, d)  #4
f("python", *t)    #5
f("python", *l, **d)   #6
f("python", q="winning", **d)   #7

思路

题目不难,但很容易漏,就像在#1中,实际上给关键字参数**kwargs什么都没传,打印时,仍然会打印个空字典{},同样在#3中,可变参数*args位置上什么都没传,仍然会打印个空元组()
值得注意的还有#4ld,由于都没有解包,所以当做一个元组([1, 2, 3], {"a": 7, "b": 8, "c": 9})传进去了

结果

1 (2,) {}
1 (2, 3, ‘python‘) {}
python () {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
python ([1, 2, 3], {‘a‘: 7, ‘b‘: 8, ‘c‘: 9}) {}
python (4, 5, 6) {}
python (1, 2, 3) {‘a‘: 7, ‘b‘: 8, ‘c‘: 9}
python () {‘q‘: ‘winning‘, ‘a‘: 7, ‘b‘: 8, ‘c‘: 9}

相关推荐