Sel*_*vam 0 python dictionary for-loop
假设字典包含10个以上的键值对.字典应该按值(整数)排序.打印出前10个值(和相应的键).我认为这里有一个更好的解决方案.
for keys in sorted(x):
c=c+1
if c>10:
break
else:
print keys, x['keys']
Run Code Online (Sandbox Code Playgroud)
for key in sorted(x, key=x.get, reverse=True)[:10]:
print key, x[key]
Run Code Online (Sandbox Code Playgroud)
对于非常大的,dict
你应该考虑使用heapq
from heapq import nlargest
for key in nlargest(10, x, key=x.get):
print key, x[key]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1358 次 |
最近记录: |