Python little exercise: Given a list of non-empty and positive integers, sort the output in descending order of repetition

Source: Internet
Author: User
Tags repetition

Suppose there is a list a=[1,1,1,2,2,4,5,5,5,5] (not empty and a positive integer)

Then the final output is in the form of 5,1,2,4 (the output is sorted in descending order of repetition)

Code implementation and interpretation:

a=[1,1,1,2,2,4,5,5,5,5]
Num=[]

For I in A:
s = A.count (i)
Num.append (s) #取出数字出现的次数 put into num

NUM1 = sorted (num,reverse=true) # arranges num in descending order and assigns a value to NUM1
Num2=list (Set (NUM1)) #去重并转换成列表类型 (Note: The element display is unordered after de-weight)
Num2.sort (Key=num1.index) #按原来num1的顺序排序 (This step is critical for the value in the a list that ultimately outputs as required)
Num3=[]

For x in num2:
For I in A:
If x ==a.count (i):
Num3.append (i) #取出次数对应a列表里面的值放进新列表num3中 the elements in the num3 are the same as the elements in a list except that the order is displayed in repetitions and the elements have duplicate values
Else
Pass
Num4=[]
For J in Num3:
If J not in NUM4:
Num4.append (j) #去重
Print (NUM4)

The final output is: [5, 1, 2, 4]

Here's a list of knowledge points to go back to and sort by the original order:

Num2=list (Set (NUM1)) #去重并转换成列表类型  (Note: The element display is unordered after de-weight)
Num2.sort (Key=num1.index) #按原来num1的顺序排序 (This step is critical for the value in the a list that ultimately outputs as required)

Python little exercise: Given a list of non-empty and positive integers, sort the output in descending order of repetition

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.