在使用max之后,如何知道python中哪个变量的值最大?

2024-05-16 08:50:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在for循环中有一些变量,我必须找到它们中的最高值,以及具有最高值的变量的名称

我使用了:

highest_value = max(a,b,c,d,e)
return highest value

它给了我正确的答案,但我无法识别哪一个变量的值最高

以下是实际代码:

def highest_area(self):
        southeast = 0
        southwest = 0
        northeast = 0
        northwest = 0
        others = 0
    
    for i in self.patient_region:
        if i=="southeast":
            southeast += 1
        elif i=="southwest":
            southwest += 1
        elif i=="northeast":
            northeast+=1
        elif i=="northwest":
            northwest+=1
        else:
            others+=1
    highest = max(southeast,southwest,northeast,northwest,others)
    return highest

如何使用任何内置函数获取最高值的名称


Tags: 答案代码self名称forreturnvaluemax
3条回答

可以使用字典而不是多个变量来执行此操作。您将使用变量名作为字典的键,变量的值将是字典中的值。例如,考虑FoLLoWIN代码:

myDict = {'a': 1, 'b': 2, 'c': 3}
print(max(myDict, key=myDict.get))

它将输出

'c'

这是字典中最高键的名称

因此,对于您的代码,实现这一点看起来像:

directions = {
        'southeast' : 1,
        'southwest' : 2,
        'northeast' : 3,
        'northwest' : 4,
        'others' : 5
        }

max_direction = max(directions, key=directions.get)
a = self.patient_region
print(max(set(a), key = a.count))

您应该使用字典来存储变量

以下是您的代码-简化:

from operator import itemgetter

def highest_area(self):
        directions = dict(
          southeast = 0
          southwest = 0
          northeast = 0
          northwest = 0
        )
        others = 0
    
    for i in self.patient_region:
        if i in directions:
            directions[i] += 1
        else:
            others += 1
    directions['others'] = others
    # highest_dir has the key, while highest_val has the corresponding value
    highest_dir, highest_val = max(directions.items(), key=itemgetter(1))
    return highest_dir 

相关问题 更多 >