# 一道面试题：去重排序

## 解1

def count_list_1(data:list):
res = {}
for item in data:
if item not in res.keys():
res[item] = 1
else:
res[item] += 1
return dict(sorted(res.items(), key=lambda i:i[1], reverse=True))

print(count_list_1(["a", "b", "g", "g", "b", "g", "l", "k", "k"]))

# 返回
{'g': 3, 'b': 2, 'k': 2, 'a': 1, 'l': 1}

## 解2

def count_list_2(data:list):
res = {}
for item in data:
res[item] = data.count(item)
return dict(sorted(res.items(), key=lambda i:i[1], reverse=True))

print(count_list_2(["a", "b", "g", "g", "b", "g", "l", "k", "k"]))

# 返回
{'g': 3, 'b': 2, 'k': 2, 'a': 1, 'l': 1}

## 解3

import collections

def count_list_3(data:list):
return dict(sorted(collections.Counter(data).items(), key=lambda i: i[1], reverse=True))

print(count_list_3(["a", "b", "g", "g", "b", "g", "l", "k", "k"]))

# 返回
{'g': 3, 'b': 2, 'k': 2, 'a': 1, 'l': 1}

## 消耗时间对比

# 统计列表中的重复的元素的个数, 并对结果进行排序
# ["a", "b", "g", "g", "b", "g"] => {"a": 1, "b":2, "g": 3}
import collections
import random
import string

def count_list_1(data: list):
res = {}
for item in data:
if item not in res.keys():
res[item] = 1
else:
res[item] += 1
return dict(sorted(res.items(), key=lambda i: i[1], reverse=True))

def count_list_2(data: list):
res = {}
for item in data:
if item not in res.keys():
res[item] = data.count(item)
return dict(sorted(res.items(), key=lambda i: i[1], reverse=True))

def count_list_3(data: list):
return dict(sorted(collections.Counter(data).items(), key=lambda i: i[1], reverse=True))

if __name__ == "__main__":
data = [random.choice(string.ascii_letters) for i in range(10000)]
count_list_1(data)
count_list_2(data)
count_list_3(data)

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1    0.002    0.002    0.003    0.003 test.py:9(count_list_1)
1    0.001    0.001    0.010    0.010 test.py:19(count_list_2)
1    0.000    0.000    0.000    0.000 test.py:27(count_list_3)

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1    0.010    0.010    0.013    0.013 test.py:9(count_list_1)
1    0.006    0.006    0.044    0.044 test.py:19(count_list_2)
1    0.000    0.000    0.002    0.002 test.py:27(count_list_3)

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1    0.020    0.020    0.026    0.026 test.py:9(count_list_1)
1    0.012    0.012    0.090    0.090 test.py:19(count_list_2)
1    0.000    0.000    0.004    0.004 test.py:27(count_list_3)