当前位置:首页 >> 脚本专栏

python 统计数组中元素出现次数并进行排序的实例

如下所示:

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()

输出结果如下:

[[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 统计数组中元素出现次数并进行排序的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。