python 得到列表中每一個元素出現次數的最快方法

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)
相關文章
相關標籤/搜索