把python 數組,量化為從1開始的數組

來源:互聯網
上載者:User
問題描述:

比方我有一個數組:a=[10,12,3,4,9]

我最終想要的是:[4,5,1,2,3]

就是按照大小將數組a中的元素轉換為其對應的大小排序值。


思路:1,先用字典儲存位置和值

    2,按照值對字典進行排序

       3,對排序後的值進行量化:量化為:1,2,3,4,5

    4,在對tuple按照位置進行排序

    5,匯出排序後的值即可

dict={}for i in xrange(len(FINAL_STATISTICS)):    dict.setdefault(i,FINAL_STATISTICS[i])sorted_tuple=sorted(dict.iteritems(),key=lambda dict:dict[1]) #對字典按照key值進行排序temp_list=[]temp_count=1for i in xrange(len(sorted_tuple)):    if i==0:        temp_list.append([sorted_tuple[i][0],temp_count])            #temp_count+=1        continue    if sorted_tuple[i][1]==sorted_tuple[i-1][1] :        temp_list.append([sorted_tuple[i][0],temp_count])    else :        temp_count+=1<span style="white-space:pre"></span>#對tuple的值進行量化        temp_list.append([sorted_tuple[i][0],temp_count])                temp_list  =sorted(temp_list)final_sorted=[]for item in temp_list:    final_sorted.append(item[1])      #輸出tuple的第二個元素print final_sorted


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.