python之format 报错IndexError: tuple index out of range

代码环境:
自定义了一个demo函数,返回值为一个元组。
想传入自定义函数返回的元组参数 到 format函数中使用,
结果报错
IndexError: tuple index out of range

#自定义函数,中间代码过程不用管
def demo(*p):
    max = 0
    min = p[0]
    length = len(p)
    sum = 0
    for item in p:
        if item > max:
            max = item
        if item < min:
            min =item
        sum += item
    average = sum/length
    return max,min,sum,average  
    #返回了一个元组(max,min,sum,average )
    #想直接在format函数中调用自定义函数返回的参数
    print("最大值为{0[0]},最小值为{0[1]},平均值为{0[3]}".format(demo(21,23,13,45,12,65,4,75,453,20)))

原因是
format函数会自动将参数转换成一个元组,所以如果你本来想传入一个元组参数到format函数中的话,实际上参数为长度为1的元组中嵌套你传的元组。
所以前面的{0},{1},{2}…要改成 {0[0]} {0[1]}…

你可能感兴趣的:(python)