[Python] python vs cplusplus

來源:互聯網
上載者:User

標籤:bug   value   預設   eve   ret   html   通過   ict   sorted   

一些學習過程中的總結的兩種語言的小對比,協助理解OO programming.

Continue...

 

字典

 

  • 序列 --> 字典

Python:

def get_counts(sequence):    counts = {}    for x in sequence:        if x in counts:            counts[x] += 1        else:            counts[x] = 1    # 這是是硬傷,不優於c++,這裡必須如此寫    return counts

 

c++:貌似沒有這個問題。

#include <iostream>#include <map>using namespace std;int main(){    cout << "Hello World!" << endl;    map<string, int> m;//    m["a"] = 1;//    m["a"] += 1;    cout << m.size() << endl;    cout << m["a"] << endl;  //自動添加了"a"    cout << m.size() << endl;    return 0;}

 

  • 字典排序

C++ sort參考:

[c++] Associative Containers

 

python sort:

counts = get_counts(time_zones)# counts.sort() 錯誤的,預設按照第一個屬性排序print(type(counts)) # debug

如果是自訂排序呢?

python 字典(dict)的特點就是無序的,按照鍵(key)來提取相應值(value),

如果我們需要字典按值排序的話,那可以用下面的方法來進行:

(1) 下面的是按照value的值從大到小的順序來排序。

dic = {‘a‘:31, ‘bc‘:5, ‘c‘:3, ‘asd‘:4, ‘aa‘:74, ‘d‘:0}#dic.iteritems() 得到[(鍵,值)]的列表。#然後用sorted方法,通過key這個參數,指定排序是按照value,也就是第2個元素d[1]的值#來排序。reverse = True表示是需要翻轉的,預設是從小到大,翻轉的話,那就是從大到小。dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)print dict


(2) 對字典按鍵(key)排序:

dic = {‘a‘:31, ‘bc‘:5, ‘c‘:3, ‘asd‘:4, ‘aa‘:74, ‘d‘:0}dict= sorted(dic.iteritems(), key=lambda d:d[0]) # 按照第2個元素d[1]的值來排序print dict

 

 

[Python] python vs cplusplus

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.