ImportCollectionsImportNumPy as NPImportRandomImport Timedeflist_to_dict (LST): DiC= {} forIinchLst:dic[i]=Lst.count (i)returnDiCdefCollect (LST):returnDict (collections. Counter (LST))defUnique (LST):returnDict (Zip (*np.unique (LST, return_counts=True )))defGenerate_data (num=1000000): returnNp.random.randint (NUM/10, size=num)if __name__=="__main__": T1=time.time () LST=list (Generate_data ()) T2=time.time ()Print("Generate_data took:%sms"% (T2-T1))#This machine is measured 0.12msT1=T2 D1=Unique (LST) T2=time.time ()Print("Unique took:%sms"% (T2-T1))#This machine is measured 0.42msT1=T2 D2=Collect (LST) T2=time.time ()Print("Collect took:%sms"% (T2-T1))#This machine is measured 1.25msT1=T2 D3=list_to_dict (LST) T2=time.time ()Print("List_to_dict took:%sms"% (T2-T1))#the test of the machine ... It's too slow to test it down. assert(D1 = =D2)assert(D1 = = D3)
The quickest way for Python to get the number of occurrences of each element in the list