2019-01-19
阅读量:
708
函数调用不起作用
问题描述:
有一个接收四个参数的函数,我们想调用这个函数,我们有一个大小为4的列表,包含函数的所有参数。如果我们只是将列表传递给函数,则调用不起作用。
# A Python program to demonstrate need
# of packing and unpacking
# A sample function that takes 4 arguments
# and prints them.
def fun(a, b, c, d):
print(a, b, c, d)
# Driver Code
my_list = [1, 2, 3, 4]
# This doesn't work
fun(my_list)
Output :
TypeError: fun() takes exactly 4 arguments (1 given)
问题解决:
我们可以使用*解压缩列表,以便它的所有元素都可以作为不同的参数传递。
# A sample function that takes 4 arguments
# and prints the,
def fun(a, b, c, d):
print(a, b, c, d)
# Driver Code
my_list = [1, 2, 3, 4]
# Unpacking list into four arguments
fun(*my_list)
输出:(1,2,3,4)






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
0条评论