用Python程序查找列表中的第三大数[关闭] 。

问题描述 投票:-1回答:1

我有一个问题,我不知道如何返回-999,如果有一个字符串或浮动在那里。能否帮助我?'定义一个名为 "largethirdnum "的函数,该函数以一个数字(整数)列表为参数,然后该函数将识别并返回列表中的第三大数字。这个函数将识别并返回列表中的第三个最大的数字,如果参数中只有两个数字,这个函数将返回最小的数字。如果列表中只有一个数字,则函数将返回唯一的数字。如果列表中包含其他数据类型,如字符串或浮点数,它将返回-999'.这是我的代码,它一直返回-999,即使我输入整数。

def largethirdnum2(numbers):
    for i in numbers: #loop to check if all types are int
        if not isinstance(numbers, int):
            return -999
            break
        elif (len(numbers)<=2): #if length of list is less than 2 (if only 1, min is the only value)
            return min(numbers)
            break
        else:
            return (sorted(numbers)[-3]) #sort list and return the 3rd highest value
            break
python basic
1个回答
0
投票

给你。

def largethirdnum(ints):
    if type(ints) != list:
        return -999
    try:
        ints = sorted(ints)
    except TypeError:
        return -999
    if len(ints) <= 2:
        return ints[0]
    return ints[-3]

print(largethirdnum([5, 2, 3, 4]))

0
投票
if not isinstance(num, int):
    return -999

isinstance 检查一个变量是否为某一类型。


0
投票

type(i) != int 检查列表中的所有值是否为int。type(numbers) != list 检查通过的参数是否是一个列表。

def largethirdnum(numbers):
    for i in numbers:
        if type(i) != int:
            return -999
    if type(numbers) != list:
        return -999
    elif len(numbers)<=2:
        return min(numbers)
    else:
        #your code for finding third largest element
        #eg. return (sorted(numbers)[-3])

0
投票

拓展一下@红衣骑士的回答。

def largethirdnum(numbers):
    for i in numbers: #loop to check if all types are int
        if type(i)!= int:
            return -999
        elif (len(numbers)<=2): #if length of list is less than 2 (if only 1, min is the only value)
            return min(numbers)
        else: 
            return (sorted(numbers)[-3]) #sort list and return the 3rd highest value
© www.soinside.com 2019 - 2024. All rights reserved.