0%

Python笔记

根据list中存放dict的某一属性排序

1
2
3
4
Data = [{"name":'a',"value":6},{"name":'b',"value":2},{"name":'c',"value":3},{"name":'d',"value":4},{"name":'e',"value":5}]
Data.sort(key=lambda k: (k.get('value', 0))) # 升序
Data.sort(reverse = True,key=lambda k: (k.get('value', 0))) # 降序
print Data

多维数据排序

1
2
3
4
5
Data = [[1,2,3],[4,5,6],[3,2,1],[6,5,4],[7,8,9]]
Data.sort(key=lambda k:k[2])
Data.sort(key=lambda k:k[1])
Data.sort(key=lambda k:k[0])
print Data

将函数和函数所需要的参数做为一个函数的参数传入

1
2
3
4
5
6
7
8
9
def fx(x,a,b,c,d,e):
return a*x*x*x*x+b*x*x*x+c*x*x+d*x+e
def setPredictData(fun,argarray):
_ylist = []
for i in range(0,5):
_y = fun(i,*argarray)
_ylist.append(_y)
return _ylist
print setPredictData(fx,[1,2,3,4,5])

更换python运行目录到脚本目录

1
2
3
4
5
6
def loadconf(conf_path):
_runpath = os.getcwd()
os.chdir(sys.path[0])
cf = ConfigParser.ConfigParser()
cf.read(conf_path)
os.chdir(_runpath)

读取json文件并解析

1
2
3
4
5
6
import json
def load():
with open('data.json') as json_file:
data = json.load(json_file)
return data
print load()

plt设置显示中文

1
2
# 设置字体文件,否则不能显示中文  
myfont = matplotlib.font_manager.FontProperties(fname='c:\\windows\\fonts\\fzshjw_0.ttf')

从命令行传入参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help","input=","output="])
except getopt.GetoptError:
usage()
sys.exit(2)
infile = outfile = ""
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i", "--input"):
infile = a
elif o in ("-o", "--output"):
outfile = a
workingHoursAutomation().start(infile,outfile)