擅长:python、mysql、java
<P>而不是查看^ {< CD1> }考虑使用^ {CD2>}。这将为您提供键/值对。您可以在生成器表达式中使用它并调用<code>next()</code>来获取键的值<code>next()</code>在没有可返回的内容时采用默认值。例如:</p>
<pre><code>def winner(votes):
d = {}
for i in votes:
if i not in d:
d[i]=1
else:
d[i] = d[i]+1
# get the key for a value that's greater than half
# or NOTA if there isn't one
return next((k for k, v in d.items() if v > len(votes)//2), 'NOTA')
winner(['a','b','a','a','b','b', 'b'])
# 'b'
winner(['a','b','a','a','b','b'])
# NOTA
</code></pre>
<p>在用这种方法解决了<a href="https://docs.python.org/3.7/library/collections.html#collections.Counter" rel="nofollow noreferrer">^{<cd5>}</a>之后,您还应该看看它</p>