python 常用函数整理(持续更新)
1.数字前置补0 ,格式化
# 方式一
str(123).zfile(5) # 00123
# 方式二
"%05d" % 123 # 00123
2. 向下取整,向上取整
import math
math.floor(2.5) # 2.0
math.ceil(2.4) # 3.0
3. 将字符序列写入文件
fileobj.writelines(["123\n", "456"]) # 123\n456
注意:参数可以是迭代器
4.读取文件并且按行分割成列表
fileobj.read().split() # 返回的是:每行作为一个列表元素的列表/数组
5.map, reduce, zip函数的使用
# map
# 对于可迭代对象进行迭代对于元素应用函数,如果有多个参数,构造为元组应用于函数
# 返回值为列表 2.x
In [17]: map(lambda x, y:x + y, [1,2,3], [4,5,6])
Out[17]: [5, 7, 9]
In [7]: map(lambda *_: _, [1,2,3], [4,5,6])
Out[7]: [(1, 4), (2, 5), (3, 6)]
# zip 可以实现相同作用 ,打包为元组
In [10]: zip([1, 2, 3], [4, 5, 6])
Out[10]: [(1, 4), (2, 5), (3, 6)]
# reduce
# 不断的对两个值进行应用函数,过程是 将前两个数应用于函数,然后结果和第三个函数应用函数
In [9]: reduce(lambda _, __: _ + __, [1,2,3])
Out[9]: 6
6.获取类(实例)中的所有函数
dir(OneClass)
# ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'filtration', 'test', 'test_filter']
# 注意下划线开始的一般是内置的一些函数,不建议直接被外部使用的函数
7. 获取函数的参数个数
def test(self, arg2):
pass
print test.func_code.co_argcount
# 2
# python 3
print(test.__code__.co_argcount)
# 2
8.print 打印出列表中的中文字符
# coding=utf8
import json
x = [u'\u70ed\u654f100*100']
print json.dumps(x, ensure_ascii=False)