標籤: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