在使用max之后,如何知道python中哪个变量的值最大?
我在for循环中有一些变量,我必须找到它们中的最高值,以及具有最高值的变量的名称 我使用了:在使用max之后,如何知道python中哪个变量的值最大?,python,max,Python,Max,我在for循环中有一些变量,我必须找到它们中的最高值,以及具有最高值的变量的名称 我使用了: highest_value = max(a,b,c,d,e) return highest value 它给了我正确的答案,但我无法识别哪一个变量的值最高 以下是实际代码: def highest_area(self): southeast = 0 southwest = 0 northeast = 0 northwest = 0
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
如何使用任何内置函数获取最高值的名称?您可以使用字典而不是多个变量来完成此操作。您将使用变量名作为字典的键,变量的值将是字典中的值。例如,考虑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=自我患者区域
printmaxseta,key=a.count
我不确定这是否是最好的解决方案,但是:
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]
您应该使用字典来存储变量 以下是您的代码-简化:
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标准库中的计数器和itemgetter内置项可以实现以下功能:
从收款进口柜台
从运算符导入itemgetter
def最高_区域自身:
计数=反自我患者\区域
最大方向,最大值=maxcounts.items,键=itemgetter1
想退什么就退什么
计数器是一个字典,如果您检查一个不存在的键,它默认包含0。其行为如下:
c=计数器
打印计数器
c['northwest']+=1
printc计数器{'1}
itemgetter位只告诉max使用键的第二个元素count tuple来选择最大值
这只是缺少代码中的另一个类别,因此您只需检查max_方向是否是您期望的四个方向之一。使用带有“东南”等键的字典,您的问题会得到更好的解决,“西南”等。所以我应该制作一个字典,并将值分配给键,然后打印整个字典,以知道哪个是最高的?哦,我从来没有想过。和你之前的答案类似,这一个出现在低质量的评论队列中。我们鼓励您在答案中添加比代码更多的信息,否则您将面临删除答案的风险。始终解释代码也是一种很好的做法。