ValueError: max() arg is an empty sequence

前端 未结 5 2426
礼貌的吻别
礼貌的吻别 2021-01-03 18:37

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

5条回答
  •  悲&欢浪女
    2021-01-03 18:51

    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.

    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.

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

    Correct way is:

    if frequencies.get(name):
    

    And Pythonic way is:

    if name in frequencies:
    

    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() 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 "", line 1, in 
        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 if on them directly:

    >>> 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 value for min() and max() in case of empty iterable.

提交回复
热议问题