How to count the frequency of the elements in an unordered list?

后端 未结 30 3244
时光说笑
时光说笑 2020-11-22 02:37

I need to find the frequency of elements in an unordered list

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

output->

b =         


        
30条回答
  •  执念已碎
    2020-11-22 02:48

    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    
    # 1. Get counts and store in another list
    output = []
    for i in set(a):
        output.append(a.count(i))
    print(output)
    
    # 2. Remove duplicates using set constructor
    a = list(set(a))
    print(a)
    
    1. Set collection does not allow duplicates, passing a list to the set() constructor will give an iterable of totally unique objects. count() function returns an integer count when an object that is in a list is passed. With that the unique objects are counted and each count value is stored by appending to an empty list output
    2. list() constructor is used to convert the set(a) into list and referred by the same variable a

    Output

    D:\MLrec\venv\Scripts\python.exe D:/MLrec/listgroup.py
    [4, 4, 2, 1, 2]
    [1, 2, 3, 4, 5]
    

提交回复
热议问题