min() on collections.defaultdict() returns max count

只谈情不闲聊 提交于 2019-12-10 23:35:18

问题


When using min() on a defaultdict object, it strangely returns the maximum if used on a dict counting indices of a string.

For example:

>>> import collections
>>> defaultdict=collections.defaultdict
>>> x=defaultdict(int)
>>> string="lol I am a lol noob"
>>> for k in string:
    x[k]+=1


>>> x
defaultdict(<type 'int'>, {'a': 2, ' ': 5, 'b': 1, 'I': 1, 'm': 1, 'l': 4, 'o': 4, 'n': 1})
>>> min(x.items())
(' ', 5)

回答1:


items() returns the items as (key, value) tuples. This means that when they are compared by min (or by anything else), they are compared first by key and then by value. Since ' ' is the "minimum" string (i.e., ' ' < 'a', ' ' < 'b', etc.), that is what is returned.

You need to tell min to use the second item of the tuple as the comparison key. Do min(x.items(), key=lambda a: a[1]).



来源:https://stackoverflow.com/questions/13062566/min-on-collections-defaultdict-returns-max-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!