我想生成一个报告,其中第一列将包含我的SQL查询的持续时间。那应该按照最长持续时间到最低持续时间进行排序。
代码:
import os
directory = "./"
results = {}
def isfloat(value):
try:
float(value)
return True
except ValueError:
pass
for root,dirs,files in os.walk(directory):
for file in files:
if file.endswith(".csv"):
input_file=open(file, 'r')
for line in input_file:
if line:
try:
duration=line.split(',')[13].split(' ')[1]
if isfloat(duration): # check if string is a float
results[duration]=line
except:
pass
output_file = open('report.csv', 'w')
for k,v in sorted(results.items()):
print k
output_file.write(k + ',' + v)
output_file.close()
输出:
1266.114
1304.450
1360.771
1376.104
1514.518
500.105
519.432
522.594
522.835
528.622
529.664
我不知道为什么sorted()
函数排序功能会弄乱我的结果?
您的密钥是字符串,而不是数字。它们按字典顺序排序。
如果要进行数字排序,请先转换为数字:
for k,v in sorted(results.items(), key=lambda k_v: float(k_v[0])):
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句