The quickest way for Python to get the number of occurrences of each element in the list

Source: Internet
Author: User
Tags assert

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

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.