在Python中查找最小变量

问题描述 投票:0回答:5

我有一些整数变量,我想找到最小的一个。当我使用时:

m1 = min(v1, v2, ...)

我得到最小的那个的,而不是它的名字。我想知道哪一个最小,不知道它的价值!我应该怎么做?

python integer minimum
5个回答
1
投票

所以您有2个变量v1和v2,并且要打印v1小或v2:

if( v1 > v2 ):
    print "v1 =": str(v1)
    #or print "v1 is smaller"  
else:
    print "v2 =": str(v2)

如果您有很多变量,那么将它们存储在字典中可能是一个更好的主意。


1
投票

如果索引号有效,则可以执行此操作:

# enter variables
a = 1
b = 2
c = 3

# place variables in list
l = (a,b,c)

# get index of smallest item in list
X = l.index(min(l))

# to print the name of the variable
print(l[X])

X,然后是最小变量的索引号(在这种情况下为0),可以根据需要使用,或者可以使用l [X]访问变量名。


0
投票
获取任何变量的名称是一个令人生厌的话题,如您在How to get a variable name as a string in Python?中所见

但是,如果上述答案中的一种解决方案是可接受的,那么您将拥有一个由变量名/值对组成的字典,您可以对它进行排序并取其最小值。例如:

vals = {"V1": 1, "V2": 3, "V3": 0, "V4": 7} sorted(vals.items(), key=lambda t: t[1])[0][0] >>> 'V3'


0
投票
def ShowMinValue(listofvalues): x = float(listofvalues[0]) for i in range(len(listofvalues)): if x > float(listofvalues[i]): x = float(listofvalues[i]) return x print ShowMinValue([5,'0.1',6,4,3,7,4,1,234,'2239429394293',234656])
返回0.1

现在,要为其设置变量,只需输入:

variable = ShowMinValue(listOfPossibleNumbers)

如果您想要一个永不例外的版本:

def ShowMinValue(listofvalues): try: x = createdMaxDef(listofnumbers) #Your maximum possible number, or create an max() def to set it. to make it, set that '>' to '<' and rename the method except Exception: pass for i in range(len(listofvalues)): try: if x > float(listofvalues[i]): x = float(listofvalues[i]) except Exception: pass return x print ShowMinValue([5,'0.1',6,4,'',3,7,4,1,234,'2239429394293',234656])

返回2239429394293(将'>'更改为'

0
投票
使用python-varname包:

https://github.com/pwwang/python-varname

from varname import Wrapper v1 = Wrapper(3) v2 = Wrapper(2) v3 = Wrapper(5) v = min(v1, v2, v3, key=lambda x:x.value) assert v is v2 print(v.name) # 'v2'

© www.soinside.com 2019 - 2024. All rights reserved.