如何计算所有变量的最小值?Python

2024-10-04 05:26:40 发布

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

我搞不懂怎么做一个函数,从所有变量中计算最小值

例如

>>>Myscore1 = 6 
>>>Myscore2 =-3
>>>Myscore3 = 10 

如果是最小值,函数将返回分数和True,否则返回False。 因此,从上述示例中,输出将是:

>>>[(6,False),(-3,True),(10,False)]

Tags: 函数falsetrue示例分数myscore3myscore1myscore2
3条回答

很简单:

>>> scores = [Myscore1, Myscore2, Myscore3]
>>> [(x, (x == min(scores))) for x in scores]
[(6, False), (-3, True), (10, False)]

使用enumerate的单行程序

scores = [6, -3, 10]

import operator
res = [[scores[i], True] 
   if i == min(enumerate(scores), key = operator.itemgetter(1))[0] 
   else [scores[i], False] 
   for i in range(len(scores))]
scores = [6, -3, 10]
def F(scores):
    min_score = min(scores)
    return [(x, x == min_score) for x in scores]

>>> F(scores)
[(6, False), (-3, True), (10, False)]

相关问题 更多 >