import collections import numpy as np import random import time def list_to_dict(lst): dic = {} for i in lst: dic[i] = lst.count(i) return dic def collect(lst): return dict(collections.Counter(lst)) def unique(lst): return dict(zip(*np.unique(lst, return_counts=True))) def generate_data(num=1000000): return np.random.randint(num / 10, size=num) if __name__ == "__main__": t1 = time.time() lst = list(generate_data()) t2 = time.time() print("generate_data took : %sms" % (t2 - t1)) # 本机实测0.12ms t1 = t2 d1 = unique(lst) t2 = time.time() print("unique took : %sms" % (t2 - t1)) # 本机实测0.42ms t1 = t2 d2 = collect(lst) t2 = time.time() print("collect took : %sms" % (t2 - t1)) # 本机实测1.25ms t1 = t2 d3 = list_to_dict(lst) t2 = time.time() print("list_to_dict took : %sms" % (t2 - t1)) # 本机实测...太慢了测不下去了 assert(d1 == d2) assert(d1 == d3)