python dict 按照value排序的试验
2017-09-05 15:58
351 查看
一般采取sorted自建函数进行排序,但考虑到Counter.most_common 可以取到前若干个,那么不妨实现并比较下二者的效率
在一台6500的机器上,输出如下:
[(9298, 25), (647, 22), (848, 22), (1365, 22), (2036, 22), (3566, 22)……
0.150000095367
[(9298, 25), (647, 22), (848, 22), (1365, 22), (2036, 22), (3566, 22)……
0.138999938965
看起来还是sorted更胜一筹,代码实现可供参考,多谢捧场
# coding:utf - 8 import copy import random import sys import time from collections import Counter from collections import defaultdict from operator import itemgetter reload(sys) sys.setdefaultencoding("utf-8")
thresh = 100000 mapper = defaultdict(int) random_creator = random.Random() const = 10000 for index in xrange(thresh): # type of float random_number = random_creator.random() mapper[int(random_number * const)] += 1 mapper_1 = copy.deepcopy(mapper) mapper_2 = copy.deepcopy(mapper) # counter start = time.time() counter = Counter(mapper_1) print counter.most_common(const) print str(time.time() - start) # sorted start = time.time() print sorted(mapper_2.iteritems(), key=itemgetter(1), reverse=True) print str(time.time() - start)
在一台6500的机器上,输出如下:
[(9298, 25), (647, 22), (848, 22), (1365, 22), (2036, 22), (3566, 22)……
0.150000095367
[(9298, 25), (647, 22), (848, 22), (1365, 22), (2036, 22), (3566, 22)……
0.138999938965
看起来还是sorted更胜一筹,代码实现可供参考,多谢捧场
相关文章推荐
- python dict按照value 排序
- python dict按照value 排序
- python dict按照value 排序
- python dict按照value 排序
- python dict按照value 排序
- 在一个list列表中的多个dict字典按照键值对key-value来进行排序
- python 中字典对象按照 value 排序
- python实现字典按value排序,以及按照key排序的实现方法
- python字典按照value进行排序
- python 对字典按照value进行排序
- Python实现字典按照value进行排序的方法分析
- python中对字典按照value排序
- Python中dict的排序方法(按key或按value)
- 转:C++中实现对map按照value值进行排序
- Python实现二维数组按照某行或列排序的方法【numpy lexsort】
- python 小程序,按照姓名或成绩排序(sorted用法)
- python 字典dict sorted 排序
- python中如何对dict对象进行排序
- python的【字典dict】:创建、访问、更新、删除;查看键、值、键值对;遍历;排序
- python 字典(dict)按键和值排序