[python] python vs Cplusplus

Source: Internet
Author: User

Some of the learning processes summarize the small contrasts between the two languages to help understand Oo Programming.

Continue ...

Dictionary

    • Series--dictionary

Python:

def get_counts (sequence):     = {}    for in  sequence:        if in counts:            + = 1        else:            = 1    #  This is a mishap, not better than C + +, here must be written     return counts

C + +: That doesn't seem to be the Problem.

#include <iostream>#include<map>using namespacestd;intmain () {cout<<"Hello world!"<<endl; Map<string,int>m;//m["a"] = 1;//m["a"] + = 1;cout<< m.size () <<endl; cout<< m["a"] <<endl; //automatically added "a" cout<< m.size () <<endl; return 0;}

    • Dictionary sort

C + + sort Reference:

[c + +] Associative Containers

Python sort:

Counts = get_counts (time_zones)#  counts.sort () error, default sorted by first property print# Debug

What if it's a custom sort?

The Python dictionary (dict) is characterized by an unordered character that extracts the corresponding value (value) according to the KEY.

If we need a dictionary sorted by value , it can be done in the following way:

(1) the following values are sorted in order of value from large to Small.

DIC = {'a': 31,'BC'75A'C': 3,'ASD': 4,'AA': 74,'D': 0} #dic. iteritems () gets a list of [(keys, values)]. #然后用sorted方法, by the key parameter, specifies that the sort is sorted by value, or 2nd element d[1]. Reverse = True indicates that it needs to be flipped, the default is small to large, flip the words, that is, from large to Small. dict= Sorted (dic.iteritems (), key=Lambdad:d[1], reverse =True)PrintDict


(2) sort the dictionary key (key):

DIC = {'a'BC'c' ASD ' ' AA ' ' D ' : 0}dict= sorted (dic.iteritems (), key=Lambda# Sort print by the value of 2nd element d[1]  Dict

[python] python vs Cplusplus

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.