Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何获得无限*args列表中最高的两个数字?_Python 3.x - Fatal编程技术网

Python 3.x 如何获得无限*args列表中最高的两个数字?

Python 3.x 如何获得无限*args列表中最高的两个数字?,python-3.x,Python 3.x,首先,如果它不在*args列表中,我知道该怎么做,但长话短说,它必须在一个创建*args列表的函数中 我正在打印列表中最大的两个数字 def findTwoLargest(*args): max1 = 0 max1 = max(args) args.sort() max2 = 0 max2 = args[-2] return max1, max2 m1, m2 = findTwoLargest(-2, 30, -4, 9, 1, 6) p

首先,如果它不在*args列表中,我知道该怎么做,但长话短说,它必须在一个创建*args列表的函数中

我正在打印列表中最大的两个数字

def findTwoLargest(*args):
    max1 = 0
    max1 = max(args)
    args.sort()
    max2 = 0
    max2 = args[-2]
    return max1, max2
    
m1, m2 = findTwoLargest(-2, 30, -4, 9, 1, 6)
print(m1, m2)

args
是一个
tuple
,因此不能对其使用
sort
方法。您可以改用
sorted
函数:

def findTwoLargest(*args):
    max1 = 0
    max1 = max(args)
    max2 = 0
    max2 = sorted(args)[-2]
    return max1, max2
    
m1, m2 = findTwoLargest(-2, 30, -4, 9, 1, 6)
print(m1, m2)
简短版本:

def findTwoLargest(*args):
    max2, max1 = sorted(args)[-2:]
    return max1, max2