我有一些整数变量,我想找到最小的变量。当我使用:在Python中查找最小变量
m1 = min(v1, v2, ...)
我得到值最小的一个,而不是它的名称。我想知道哪一个最小,不知道它的价值!我应该怎么做?
我有一些整数变量,我想找到最小的变量。当我使用:在Python中查找最小变量
m1 = min(v1, v2, ...)
我得到值最小的一个,而不是它的名称。我想知道哪一个最小,不知道它的价值!我应该怎么做?
让你有2个变量v1和v2以及要打印V1小或V2:
if(v1 > v2):
print "v1 =": str(v1)
#or print "v1 is smaller"
else:
print "v2 =": str(v2)
,如果你有很多的变量,然后将它们存储在一本字典可能是一个更好的主意。
如果指数会的工作,你可以这样做:
# 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]可用于访问变量名称。 (但是不要像我一样使用小写的“L”,通常不被认为是很好的风格,因为它很容易被误认为上层cas“i”或数字1)。
得到任何变量的名称是一个充满话题,因为你可以在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'
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(改变 '>' 到 '<')
假设'v2'是最小的。你想'm1'等于*字符串* v2'吗?或者你是否希望它等于索引1(因为Python使用基于0的索引并假设'v's都是编号的)? – unutbu
我怀疑他希望'm1'是对'v2'引用的同一个可变对象的引用。当然,他不能那样做。 –
是的,我想要v2。如果不可能,索引(2)会帮助我。 :) –