gpt4 book ai didi

python - 从 .txt 文件中排序数据

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:30 24 4
gpt4 key购买 nike

我正在通过 python 在 mysql 上运行一些查询。读取数据后,我想按百分比对它们进行排序。任何帮助都会很高兴。

我使用的写法是:

def mid_critical(controller,code):
critical = 75
mid_critical = 50

cursor = controller.cursor()
cursor.execute(code) # execute code

with open('report.txt', 'a') as f:
print("\n******************* Mid Critical: **************", file=f)
for r in cursor: #show tables one by one
if str(type(r[5])) == "<class 'decimal.Decimal'>":
percent = r[5] / r[2] * 100
if percent > mid_critical and percent < critical:
print(r[1],"\nOwner:",r[8],"\nValues:",r[5],"out of", r[2] ,"\nPercent used: %d%% \n" %(percent), file=f)

code 是正在运行的查询。

controller 是进行成功通信的凭据。

一旦写入文件是:

POC 
Owner: ACE
Values: 45.1 out of 81.5
Percent used: 55%

DESKTOP
Owner: Nan
Values: 231.8 out of 329.2
Percent used: 70%

REGRESSION
Owner: None
Values: 6.6 out of 10.2
Percent used: 64%

为了举例,我只显示了 3 个,还有 houndreds。

我正在寻找的输出是

DESKTOP 
Owner: Nan
Values: 231.8 out of 329.2
Percent used: 70%

REGRESSION
Owner: None
Values: 6.6 out of 10.2
Percent used: 64%

POC
Owner: ACE
Values: 45.1 out of 81.5
Percent used: 55%

最佳答案

要对数据进行排序,您需要从数据库中取出数据,对其进行排序,然后将其打印到文件中,而不是在每一行之后写入文件。像这样:

def calc_percent(r):
return r[5] / r[2] * 100

with open('report.txt', 'a') as f:
print("\n******************* Mid Critical: **************", file=f)
rows = []
for r in cursor: #show tables one by one
if str(type(r[5])) == "<class 'decimal.Decimal'>":
percent = calc_percent(r)
if percent > mid_critical and percent < critical:
rows.append(r)
rows.sort(key=calc_percent)

for r in rows:
percent = calc_percent(r)
print(r[1],"\nOwner:",r[8],"\nValues:",r[5],"out of", r[2] ,"\nPercent used: %d%% \n" %(percent), file=f)

关于python - 从 .txt 文件中排序数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961187/

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