【问题标题】:finding minimum variable in Python在Python中找到最小变量
【发布时间】:2015-09-28 11:36:06
【问题描述】:

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

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

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

【问题讨论】:

  • 假设v2 是最小的。你想让m1 等于字符串 'v2'吗?还是您希望它等于索引 1(因为 Python 使用基于 0 的索引并假设 vs 全部编号)?
  • 我怀疑他希望 m1 成为对 v2 所引用的同一个可变对象的引用。当然,他不能拥有那个。
  • 是的,我想要 v2。如果不可能,索引 (2) 会帮助我。 :)

标签: python integer minimum


【解决方案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] 来访问变量名。

(但不要像我一样使用小写字母“L”,通常不会被认为是好的样式,因为它很容易被误认为是大写字母“i”或数字 1)。

【讨论】:

  • 这不可能给我变量的名称,只是最低值。
【解决方案2】:

如您在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'

【讨论】:

    【解决方案3】:

    使用python-varname 包:

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

    from varname.helpers 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'
    
    

    【讨论】:

      【解决方案4】:

      所以你有 2 个变量 v1 和 v2 并且想要打印 v1 是小的还是 v2:

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

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

      【讨论】:

        【解决方案5】:
        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(将 '>' 更改为 '

        【讨论】:

          猜你喜欢
          • 2023-03-18
          • 1970-01-01
          • 1970-01-01
          • 2022-11-02
          • 1970-01-01
          • 2013-03-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多