gpt4 book ai didi

python - 如何在 Python 中对字典进行排序?

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:36 25 4
gpt4 key购买 nike

我想生成一个报告,其中我的第一列将包含我的 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() 函数排序函数会弄乱我的结果?

最佳答案

您的 key 是字符串,而不是数字。它们按字典顺序排序。

如果要数字排序,先转换为数字:

for k,v in sorted(results.items(), key=lambda k_v: float(k_v[0])):

关于python - 如何在 Python 中对字典进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35794320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com