从.txt文件排序数据

时间:2019-07-09 22:22:51

标签: python mysql sorting parsing

我正在通过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)

代码 是正在运行的查询。

控制器 是进行成功通信的凭据。

写入文件的时间是:

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,还有更多。

我想要的输出将是

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% 

3 个答案:

答案 0 :(得分:1)

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

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)

答案 1 :(得分:1)

BigO。 也许您应该考虑计算MySQL查询中的百分比,并使用ORDER BY来获得正确的订单。

然后,在python上,您已经按照想要的顺序保存了记录。

例如:

SELECT * FROM 
(
   SELECT Number1,Number2,Number1/Number2 AS Percentage
   FROM Table
) subquery
ORDER BY Percentage

然后随心所欲地处理数据

答案 2 :(得分:1)

将节添加到列表中,按最后一个元素对列表列表进行排序,然后输出列表:

from operator import itemgetter

report = []
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:
            report.append(
                (
                    str(r[1]),
                    "\nOwner:",
                    str(r[8]),
                    "\nValues:",
                    str(r[5]),
                    "out of",
                    str(r[2]),
                    "\nPercent used: %d%% \n" % (percent),
                )
            )

report.sort(key=itemgetter(-1), reverse=True)

with open("report.txt", "a") as f:
    print("\n******************* Mid Critical: **************", file=f)
    print("\n".join(report))