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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26151669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:09:44  来源:igfitidea点击:

ValueError: max() arg is an empty sequence

pythonlistfor-loop

提问by J'onn J'onzz

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.

我已经使用 wxFormBuilder 创建了一个 GUI,它应该允许用户将“企业访问者”的姓名输入到列表中,然后单击两个按钮之一以返回访问该企业的最频繁和最不频繁的访问者。

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).

我创建了一个早期版本,不幸的是,它给了我访问者的范围,而不是最常/最不常访问者的名字。我附上了我创建的 GUI 的屏幕截图,以帮助澄清问题(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 is an empty sequence

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

In relation to this line:

关于这条线:

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

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()

回答by Ashwini Chaudhary

Since you are always initialising self.listMyDatato an empty list in clkFindMostyour code will always lead to this error* because after that both unique_namesand frequenciesare empty iterables, so fix this.

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

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.

另一件事是,由于您在该方法中迭代集合,因此计算频率没有意义,因为集合仅包含唯一项目,因此每个项目的频率始终为 1。

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

最后dict.get是一个不是列表或字典的方法,所以你不能使用[]它:

Correct way is:

正确的做法是:

if frequencies.get(name):

And Pythonic way is:

而 Pythonic 的方式是:

if name in frequencies:

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

获取项目频率的 Pythonic 方法是使用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()and min()throw such error when an empty iterable is passed to them. You can check the length of vbefore calling max()on it.

max()min()在将空的可迭代对象传递给它们时抛出此类错误。你可以v在调用max()它之前检查它的长度。

>>> 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

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 ifon them directly:

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

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

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

好消息是,在Python 3.4开始,你将能够指定一个可选的返回值min()max()空可迭代的情况下。

回答by Aamish Baloch

When the length of v will be zero, it'll give you the value error.

当 v 的长度为零时,它会给你值错误。

You should check the length or you should check the list first whether it is none or not.

您应该检查长度,或者您应该首先检查列表是否为无。

if list:
    k.index(max(list))

or

或者

len(list)== 0

回答by Mohideen bin Mohammed

in one line,

在一行中,

v = max(v) if v else None

v = max(v) if v else None

>>> v = []
>>> max(v)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
>>> v = max(v) if v else None
>>> v
>>> 

回答by Ravi Bandoju

try parsing a default value which can be returned by max if length of v none

尝试解析一个默认值,如果 v 的长度为 none,则该默认值可以由 max 返回

max(v, default=0)