首页 > 编程语言 > 详细

[Python] python vs cplusplus

时间:2016-12-21 09:28:10      阅读:203      评论:0      收藏:0      [点我收藏+]

一些学习过程中的总结的两种语言的小对比,帮助理解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

原文:http://www.cnblogs.com/jesse123/p/6206246.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!