Python 数字操作

来源:互联网 发布:米兔积木机器人 编程 编辑:程序博客网 时间:2024/06/06 02:57

float保留指定位数

a = 0.017685447b = '%.5f' % a   # 保留小数点后5位

Python的defaultdict

defaultdict 能为不存在dict中的key给一个默认的value。比起普通的python dict,省去了自己判断遇到的key是否已在dict中。

from collections import defaultdict

Python的Counter

Counter是dict的一个子类

使用Couter可以很方便的统计list中每个元素出现的次数,如下:

from collections import Countera = list('aabbbcc')        # a=['a', 'a', 'b', 'b', 'b', 'c', 'c']Counter(a)                 # 输出:{'b': 3, 'a': 2, 'c': 2}

Counter还有其他更多功能。


原创粉丝点击