使用max后,我如何知道哪个变量在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

如何通过使用任何内置函数获得最大值的名称?

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

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 

max函数不会给你这些信息,但是下面使用Python标准库中的Counteritemgetter内置函数可以工作:

from collections import Counter
from operator import itemgetter
def highest_area(self):
counts = Counter(self.patient_region)
max_direction, max_value = max(counts.items(), key=itemgetter(1))
return #whatever you want to return

Counter是一个字典,如果您检查不存在的键,则默认包含0。它的行为如下:

c = Counter()
print(c) # "Counter()"
c['northwest'] += 1
print(c) # Counter({'northwest': 1})

itemgetter位只是告诉max使用(key, count)元组的第二个元素来选择最大值。

这里只缺少"other"类别,因此您可以检查max_direction是否为您期望的四个方向之一。

我不确定这是最好的解决方案,但是:

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, "southeast"), (southwest, "southwest"), (northeast, "northeast"), (northwest, "northwest"),(others, "others"), key=lambda t: t[0])
return highest[1]

最新更新