ValueError:max()arg为空序列 [英] ValueError: max() arg is an empty sequence

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

问题描述

我已经使用wxFormBuilder创建了一个GUI,该GUI应该允许用户在列表中输入企业访问者"的名称,然后单击两个按钮之一以返回最常访问和最不频繁访问该企业的访问者.

I've created a GUI using wxFormBuilder that should allow a user to enter the names of "visitors to a business" into a list and then click one of two buttons to return the most frequent and least frequent visitors to the business.

我创建了一个较早的版本,不幸的是,它给了我大量的访客,而不是最频繁/最少访客的名字.我已经附上了我创建的GUI的屏幕截图,以帮助您使问题更加清晰( http://imgur.com/XJnvo0U).

I created an earlier version that, unfortunately, gave me the range of visitors, rather than the name of the most/least frequent visitor. I've attached a screenshot of the GUI I've created to help add a little clarity to the issue ( http://imgur.com/XJnvo0U ).

新的代码版本与早期版本的代码不同,我无法抛出任何东西.相反,我一直收到此错误:

A new code version takes a different tack than the earlier version, and I can't get it to throw anything. Instead, I keep receiving this error:

ValueError:max()arg是一个空序列

关于此行:

self.txtResults.Value = k.index(max(v))

import wx
import myLoopGUI
import commands

class MyLoopFrame(myLoopGUI.MyFrame1):
    def __init__(self, parent):
        myLoopGUI.MyFrame1.__init__(self, parent)

    def clkAddData(self,parent):
        if len(self.txtAddData.Value) != 0:
            try:
                myname = str(self.txtAddData.Value)
                self.listMyData.Append(str(myname))
            except:
                wx.MessageBox("This has to be a name!")            
        else:
            wx.MessageBox("This can't be empty")




    def clkFindMost(self, parent):
        self.listMyData = []
        unique_names = set(self.listMyData)
        frequencies = {}
        for name in unique_names:
            if frequencies.get[name]:
                frequencies[name] += 1
            else:
                frequencies[name] = 0

        v = list(frequencies.values())
        k = list(frequencies.keys())
        self.txtResults.Value = k.index(max(v))


    def clkFindLeast(self, parent):
        unique_names = set(self.listMyData)
        frequencies = {}
        for name in unique_names:
            if frequencies.get(name):
                frequencies[name] += 1
            else:
                frequencies[name] = 0

        v = list(frequencies.values())
        k = list(frequencies.keys())
        self.txtResults.Value = k.index(min(v))

myApp = wx.App(False)
myFrame = MyLoopFrame(None)
myFrame.Show()
myApp.MainLoop()

推荐答案

由于您总是将self.listMyData初始化为clkFindMost中的空列表,因此您的代码将始终导致此错误*,因为在此之后unique_namesfrequencies是空的可迭代对象,请解决此问题.

Since you are always initialising self.listMyData to an empty list in clkFindMost your code will always lead to this error* because after that both unique_names and frequencies are empty iterables, so fix this.

另一件事是,由于您要用该方法遍历集合,因此计算频率没有意义,因为集合仅包含唯一项,因此每个项的频率始终为1.

Another thing is that since you're iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.

最后一个dict.get是不是列表或字典的方法,因此您不能将它与[]一起使用:

Lastly dict.get is a method not a list or dictionary so you can't use [] with it:

正确的方法是:

if frequencies.get(name):

Pythonic的方式是:

And Pythonic way is:

if name in frequencies:

获取项目频率的Python方法是使用 :

The Pythonic way to get the frequency of items is to use collections.Counter:

from collections import Counter   #Add this at the top of file.

def clkFindMost(self, parent):

        #self.listMyData = []   
        if self.listMyData:
           frequencies = Counter(self.listMyData)
           self.txtResults.Value = max(frequencies, key=frequencies.get)
        else:
           self.txtResults.Value = '' 


当将

max()min()传递给它们一个空的可迭代对象时,将引发此类错误.您可以在调用max()之前检查v的长度.


max() and min() throw such error when an empty iterable is passed to them. You can check the length of v before calling max() on it.

>>> lst = []
>>> max(lst)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    max(lst)
ValueError: max() arg is an empty sequence
>>> if lst:
    mx = max(lst)
else:
    #Handle this here

如果将它与迭代器一起使用,则需要先使用迭代器,然后再对它调用max(),因为迭代器的布尔值始终为True,因此我们不能直接在其上使用if:

If you are using it with an iterator then you need to consume the iterator first before calling max() on it because boolean value of iterator is always True, so we can't use if on them directly:

>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
       mx = max(lst)
    else:
      #Handle this here   

好消息从Python 3.4开始,您将可以如果为空,则为min()max()指定一个可选的返回值.

Good news is starting from Python 3.4 you will be able to specify an optional return value for min() and max() in case of empty iterable.

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

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