lamba函数
lambda a, b: a if (a > b) else b
json 解析
-
编码:把一个Python对象编码转换成Json字符串 json.dumps()
-
解码:把Json格式字符串解码转换成Python对象 json.loads()
-
dumps() 字典 --> 字符串 方法将 字典 类型的对象转换成 字符串类型
-
loads() 字符串 --> 字典 方法将 字符串 类型转换为字典
示例:
userFeature = {"bi_follows": bi_follows, "fans" : fans}
outJsonStr = json.dumps(userFeature)
featureDict = json.loads(outJsonStr, encoding='utf8')
json.dumps(tagDict, ensure_ascii=False) #ensure_ascii=False 将中文密文转化可可见的中文
数字格式化
a = 2.93823
b = "%.2f" % a
%nd:决定对齐与填充。n为整数;当n>0时,左填充,当n<0时,右填充。
print '%3d'%1.52
按不同进制格式化数字
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
b、d、o、x 分别是二进制、十进制、八进制、十六进制。
字典排序
support_ls= sorted(support_dic.iteritems(), key=lambda d:d[1], reverse = True)
时间格式化
import datetime
import time
currentTimestamp = int(time.time())
a = "2017-10-01 00:00:28"
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
timestamp = time.mktime(timeArray)
print a , " --> ", int(timestamp)
a = time.time()
a = 1511765389
currentTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(a))
print a, " --> ", currentTime
-
now = time.time()
-
timeNew = now + days*24*60*60 + hours*60*60 + miutes*60 + seconds
获取昨天的日期
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
父类调用子类构造函数
继承父类后,就能调用父类方法和访问父类属性,而要完成整个集成过程,子类是需要调用的构造函数的。子类不显式调用父类的构造方法,而父类构造函数初始化了一些属性,就会出现问题
方法1
def __init__(self):
Parser.__init__(self)
self.topicDict = {}
方法2
super(B,self).__init__()
方法一更直观,方法二可以一次初始化所有超类
super函数比在超累中直接调用未绑定方法更直观,但是其最大的有点是如果子类继承了多个父类,它只需要使用一次super函数就可以。然而如果没有这个需求,直接使用A.__init__(self)更直观一些。
正则调用
regExp = "[0-9]+.{1,3}[0-9]+"
outList = re.findall(regExp, content)
二分法查找插入数组
l = []
for i in range(1, 15):
r = random.randint(1, 100)
position = bisect.bisect(l, r)
bisect.insort(l, r)
print'%3d %3d' % (r, position), l
列表逆序输出
for elem in myList[::-1]:
print elem,
配置文件读取 configparser
import configparser
config = configparser.ConfigParser()
config.read("conf.dat", encoding='utf-8')
result = config.sections() # 以列表形式,返回获取所有分区
result = config.items('section1') # 才列表形式,返回指定分区下所有配置节点
result = config.get("section1", 'info') # 获取指定分区、节点的配置信息
result = config.getint('section1', 'port')
status = config.has_section('section3')
if status == False:
config.add_section('section3')
config.set('section3', 'ip', '10.77.104.194')
config.write(open('conf.dat', 'w'))
-------------------