<p>由于您总是初始化<code>self.listMyData</code>到<code>clkFindMost</code>中的空列表,您的代码将始终导致此错误*,因为在此之后<code>unique_names</code>和<code>frequencies</code>都是空的iterable,所以请修复此问题。</p>
<p>另一件事是,由于在该方法中迭代一个集合,所以计算频率毫无意义,因为集合只包含唯一的项,所以每个项的频率总是为1。</p>
<p>最后,<code>dict.get</code>是一个方法,而不是一个列表或字典,因此不能对它使用<code>[]</code>:</p>
<p>正确的方法是:</p>
<pre><code>if frequencies.get(name):
</code></pre>
<p>而Python的方式是:</p>
<pre><code>if name in frequencies:
</code></pre>
<p>获取项目频率的python方法是使用<a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="noreferrer">^{<cd7>}</a>:</p>
<pre><code>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 = ''
</code></pre>
<hr/>
<p><code>max()</code>和<code>min()</code>在向它们传递空iterable时抛出此类错误。在调用<code>max()</code>之前,可以检查<code>v</code>的长度。</p>
<pre><code>>>> 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
</code></pre>
<p>如果将其与迭代器一起使用,则需要先使用迭代器,然后再对其调用<code>max()</code>,因为迭代器的布尔值始终是<code>True</code>,因此不能直接对其使用<code>if</code>:</p>
<pre><code>>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
mx = max(lst)
else:
#Handle this here
</code></pre>
<p>好消息是,从Python 3.4开始,在iterable为空的情况下,您将能够为<code>min()</code>和<code>max()</code>使用<a href="https://docs.python.org/3/whatsnew/3.4.html#other-language-changes" rel="noreferrer">specify an optional return value</a>。</p>