python---按重復數字的次數 降序排列 返回數組


假設有個列表  a=[1,1,1,2,2,4,4,5,5,5,5,5] (非空且為正整數)

那么根據要求 最終輸出的形式為  [5, 1, 2, 4]  (按重復次數 降序排列輸出)

方法一:通過列表實現

# -*- coding: UTF-8 -*-
#取出數字出現的次數放進L中,並降序排序
L=[]
a=[1,1,1,2,2,4,4,5,5,5,5,5]
for i in a:
 L.append(a.count(i))
L = list(set(L))
L.sort(reverse=True)

#取出次數對應a列表里面的值放進新列表num1中
num1=[]
for m in L:
 for n in a:
  if m == a.count(n):
   num1.append(n)

#去重
num2=[]
for i in num1:
 if i not in num2:
  num2.append(i)
  
print num2

 

方法二:通過字典實現

#將數字和對應重復次數作為key,value放入字典
List=[1,1,1,2,2,5,4,4,5,5,5,5,5]
a = {}
for i in List:
    if List.count(i)>=1:
        a[i] = List.count(i)        
#對字典value(重復次數)降序排序,以列表形式返回
a = sorted(a.items(), key=lambda item:item[1],reverse=True)
>>>[(5, 6), (1, 3), (2, 2), (4, 2)]
num=[]
#獲取列表中每個元組中的第一個值,即數組中的數字(此時已是按重復次數降序)
for item in a:
    num.append(item[0])
print num
>>>[5, 1, 2, 4]
 
#items函數,將一個字典以列表的形式返回,因為字典是無序的,所以返回的列表也是無序的
#內建函數 sorted 方法返回的是一個新的 list

sorted(iterable,key,reverse),sorted一共有iterable,key,reverse這三個參數。

其中iterable表示可以迭代的對象,例如可以是dict.items()、dict.keys()等,key用來決定按什么排序,reverse則是用來指定排序是倒序還是順序,reverse=true則是倒序,reverse=false時則是順序,默認時reverse=false。


   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM