Python很常用很基础的点
Peng's Blog 只记录和技术相关的东西

Python很常用很基础的点

2017-07-01

函数

def name(xxxx):
    xxx
    xxx

然后在其他类里面需要引用这个类,最后调用方法

键值对

在Python中没有map,有键值对形式的叫 dict,字典。定义方式为: xxx = dict()

线程睡眠方法

import time time.sleep(60) 里面是秒

三目运算符:

​ 跟Java不同

xxx = 值1 if 条件 else 值2

如:maxLength = beforeLength if beforeLength > endLength else endLength

关于日期的加减以及时间的加减:

import datetime
now = datetime.datetime.now()
startTime = now;
startTime = str(startTime)
startTime = startTime[0:19]
startTime = startTime.replace('-', '')
print(startTime)
nextTime = now + datetime.timedelta(minutes=1)
nextTime = str(nextTime)
nextTime = nextTime[0:19]
nextTime = nextTime.replace('-', '')
print(nextTime)

key-value类型的数据结构里,按照value排序,顺序或倒序 。reverse=True

def sort_by_value(d):
    items = d.items()
    backitems = [[v[1], v[0]] for v in items]
    backitems.sort(reverse=True)
    return [backitemsi for i in range(0, len(backitems))]

也可以一句话搞定:

dictAllGroups2 = sorted(dictAllGroups.items(), key=lambda d: d[1],reverse=True)

lambda 作用是隐藏函数名

key-value 遍历字典

for key, value in dict(groupDict).items():
    print(key)
    print(value)

md5加密:

import hashlib
print(hashlib.new("md5", "233".encode('utf-8')).hexdigest())    

线程池 threadpool

import time
import threadpool 
def sayhello(str):
    print "Hello ",str
    time.sleep(2)
name_list =['xiaozi','aa','bb','cc']
start_time = time.time()
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(sayhello, name_list)
[pool.putRequest(req) for req in requests]
pool.wait()
print '%d second'% (time.time()-start_time)

文件操作 import codecs

 f = codecs.open(xxx.txt, a, utf-8)   // 以追加写的形式打开

上一篇 Linux基础指令

Comments

评论功能暂停使用,如需跟作者讨论请联系底部的GitHub