简体   繁体   English

Python按降序排序Collections.DefaultDict

[英]Python Sort Collections.DefaultDict in Descending order

I have this bit of code: 我有这段代码:

    visits = defaultdict(int)
    for t in tweetsSQL:
         visits[t.user.from_user] += 1

I looked at some examples online that used the sorted method like so: 我在网上看了一些使用排序方法的例子:

sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True)

but it is giving me: 但是它给了我:

"TypeError: 'builtin_function_or_method' object is not iterable"

I am not sure why. 我不知道为什么。

iteritems is a method. iteritems是一种方法。 You need parenthesis to call it: visits.iteritems() . 你需要括号来调用它: visits.iteritems()

As it stands now, you are passing the iteritems method itself to sorted which is why it is complaining that it can't iterate over a function or method. 就像现在一样,你正在将iteritems方法本身传递给sorted ,这就是为什么它抱怨它不能迭代一个函数或方法。

Personally I think one of these forms is a little more succinct as the first argument only needs to be an iterable not an iterator. 我个人认为其中一种形式更简洁,因为第一个参数只需要是迭代而不是迭代器。

sorted_keys = sorted(visits.keys(), reverse=True)
sorted_keys = visits.keys().sort(reverse=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM