min() arg 空序列 [英] min() arg empty sequence

查看:38
本文介绍了min() arg 空序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning object oriented concepts in python. Below, I have created a class and a method in it. I am trying to find the minimum of a list by directly calling the min() function and also by calling the class method findMin().

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

The below code gives me an error:

min() arg 是一个空序列

min() arg is an empty sequence

请告诉我我在这里遗漏了什么.

Please tell me what I am missing here.

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)

推荐答案

你把 numsself.nums 混淆了.

You are confusing nums with self.nums.

当你写作时:

    nums=list()

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

You are setting a variable on the class.

当你写作时:

    def findMin(self, nums):

您正在接收局部变量中的参数,nums.

You are receiving the parameter in a local variable, nums.

当你在接下来的两行写 self.nums 时,你引用了实例的 nums 变量,它被初始化为类的 nums 变量,即空列表.

When you then write self.nums on the next two lines, you're referencing the instance's nums variable, which was initialized to the value of the class's nums variable, which was the empty list.

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

As such, you are essentially sorting an empty list and then trying to find its minimum. This isn't going to work, since there's no value in an empty list to find the minimum of.

因此,您看到的错误:

ValueError: min() arg is an empty sequence

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

To solve this, use nums rather than self.nums, because then you'll be referencing the parameter rather than the instance field.

这篇关于min() arg 空序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆