我不知道如何在 Django 中以正确的顺序显示 collections.Counter:当我使用 Counter().most_common(5) 时,它应该按顺序给我 5 个最常用的键。但事实并非如此。
我有这个:
users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_common(5))
return render(request,'admin/stats/stats.html', { 'users_cities': users_cities, }
但是当我在模板中循环遍历它们时,它们没有排序:
{% for label , counter in users_cities.items %}
{% if label %}
<tr>
<th>{{ label }}</th><td> {{ counter }}</td>
</tr>
{% endif %}
{% endfor %}
那么我的错误在哪里呢?
最佳答案
您提取了最常见的内容,然后将它们放回新的字典中。字典是无序的。
跳过 dict
调用,只遍历从 most_common
获得的结果。
关于python - 渲染计数器集合排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39410954/