如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
lis = [ 12 , 34 , 456 , 12 , 34 , 66 , 223 , 12 , 5 , 66 , 12 , 23 , 66 , 12 , 66 , 5 , 456 , 12 , 66 , 34 , 5 , 34 ] def test1(): #进行去重 c = [] for i in lis: if i not in c: c.append(i) #进行统计,生成二维列表 b = [] for i in c: num = 0 for j in range ( len (lis)): if lis[j] = = i: num + = 1 a = [] a.append(i) a.append(num) b.append(a) # 排序算法,按出现次数进行降序排列 for i in range ( len (b)): for j in range (i, len (b)): if b[i][ 1 ] < b[j][ 1 ]: temp = b[i] b[i] = b[j] b[j] = temp print (b) def test2(): # set进行去重,进行统计生成二维列表 b = [] for i in list ( set (lis)): num = 0 for j in range ( len (lis)): if lis[j] = = i: num + = 1 a = [] a.append(i) a.append(num) b.append(a) # 排序算法,按出现次数进行降序排列 for i in range ( len (b)): for j in range (i, len (b)): if b[i][ 1 ] < b[j][ 1 ]: temp = b[i] b[i] = b[j] b[j] = temp print (b) def test3(): # 统计元素出现次数,元素为key,次数为value,生成字典 a = {} for i in lis: if i in a: a[i] = a[i] + 1 else : a[i] = 1 # 使用sorted对字典进行排序 b = sorted (a.items(),key = lambda item:item[ 1 ],reverse = True ) print (b) def test4(): from collections import Counter import operator #进行统计 a = dict (Counter(lis)) #进行排序 b = sorted (a.items(), key = operator.itemgetter( 1 ),reverse = True ) print (b) if __name__ = = '__main__' : test1() test2() test3() test4() |
输出结果如下:
1
2
3
4
|
[[ 12 , 6 ], [ 66 , 5 ], [ 34 , 4 ], [ 5 , 3 ], [ 456 , 2 ], [ 223 , 1 ], [ 23 , 1 ]] [[ 12 , 6 ], [ 66 , 5 ], [ 34 , 4 ], [ 5 , 3 ], [ 456 , 2 ], [ 23 , 1 ], [ 223 , 1 ]] [( 12 , 6 ), ( 66 , 5 ), ( 34 , 4 ), ( 5 , 3 ), ( 456 , 2 ), ( 23 , 1 ), ( 223 , 1 )] [( 12 , 6 ), ( 66 , 5 ), ( 34 , 4 ), ( 5 , 3 ), ( 456 , 2 ), ( 23 , 1 ), ( 223 , 1 )] |
这是面试过程中遇到的一个问题找到的解决方法,总结了一下,小编是初学者,还需不断努力学习。
以上这篇python 统计数组中元素出现次数并进行排序的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/li532331251/article/details/78854314