关于Python * args

时间:2018-02-17 23:41:50

标签: python args

import math

def square(*args):
    return math.pow(args,2)

a=[]

for i in range(1,101):

    a.append(i)

print(list(map(square,a)))

这段代码有什么问题吗?我收到了这个错误:

TypeError: must be real number, not tuple

1 个答案:

答案 0 :(得分:0)

正如@heemayl在评论中提到的那样,args是一个元组。因此,要访问元组的单个元素,您需要使用索引器:

def square(*args):
    return math.pow(args[0], 2)

或者,如果您只提供一个参数,则可以直接传递它,并且需要解压缩元组:

def square(x):
    return math.pow(x, 2)