【问题标题】:min() arg empty sequencemin() arg 空序列
【发布时间】:2016-06-01 09:02:40
【问题描述】:

我正在学习 Python 中的面向对象概念。下面,我在其中创建了一个类和一个方法。我试图通过直接调用min() 函数以及调用类方法来找到列表的最小值 findMin()

下面的代码给了我一个错误:

min() arg 是一个空序列

请告诉我我在这里缺少什么。

class Solution:
    nums = list()
    def findMin(self, nums):
        self.nums.sort()
        out = min(self.nums)
        return out

x = [4,5,6,7,0,1,2]
y = Solution()

print min(x)
print y.findMin(x) 
print len(x)
print type(y)
print dir(y)

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您将numsself.nums 混淆了。

    当你写作时:

        nums=list()
    

    您正在为类设置一个变量。

    当你写作时:

        def findMin(self, nums):
    

    您在局部变量nums 中接收参数。

    当您在接下来的两行中写入 self.nums 时,您将引用实例的 nums 变量,该变量已初始化为类的 nums 变量的值,即空列表。

    因此,您实际上是在对一个空列表进行排序,然后尝试找到它的最小值。这是行不通的,因为在空列表中没有值可以找到最小值。

    因此,您看到的错误:

    ValueError: min() arg is an empty sequence
    

    要解决这个问题,请使用nums 而不是self.nums,因为那样您将引用参数而不是实例字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2014-11-26
      • 2022-01-23
      相关资源
      最近更新 更多