排序和排名列表python并使用python写回MySQL

时间:2013-03-14 17:31:25

标签: python mysql-python

我正在使用python从MySQL读取值然后对列表进行排序。然后我需要对列表进行排名并将其写回MySQL。我的代码是

获取列表

cursor.execute ("SELECT winnings, user, rank FROM round_lb WHERE r_id = 5")
round_test = cursor.fetchall()

返回

((90L, 70L, 0L), (17L, 1L, 0L), (25L, 78L, 0L))

排序列表(所以最高奖金列是第一个)

print sorted(round_test, reverse =True)
[(90L, 70L, 0L), (25L, 78L, 0L), (17L, 1L, 0L)]

我现在想给排名字段赋值,所以90是rank1,25 rank2和17 rank3等......

这就是我被卡住的地方..有没有人知道在python中对它们进行排名的简单方法...所以我可以把它们写回MySQL ......

2 个答案:

答案 0 :(得分:4)

>>> [row[:-1] + (rank,) for rank, row in enumerate(sorted(rows, reverse=True), start=1)]
    [(90L, 70L, 1), (25L, 78L, 2), (17L, 1L, 3)]
  • enumerate(rows, start=1)返回返回(rank,row)元组的列表,从1开始
  • row[:-1]获取所有项目但最后一行(有效地删除旧排名)
  • row[:-1] + (rank,)连接行的第一项和包含排名的1元组。

如果您打算替换它,为什么要选择排名呢?

cursor.execute ("SELECT winnings, user FROM round_lb WHERE r_id = 5")
rows = cursor.fetchall()
for rank, (winnings, user) in enumerate(sorted(rows, reverse=True), start=1):
    params = (winnings, user, rank)
    cursor.execute("INSERT INTO round_lb (winnings, user, rank) VALUES (%s, %s, %s)", params)

为什么不在MySQL中对它们进行排序?

cursor.execute ("SELECT winnings, user FROM round_lb WHERE r_id = 5 ORDER BY winnings DESC")
rows = cursor.fetchall()
for rank, (winnings, user) in enumerate(rows, start=1):
    params = (winnings, user, rank)
    cursor.execute("INSERT INTO round_lb (winnings, user, rank) VALUES (%s, %s, %s)", params)

答案 1 :(得分:0)

如果您只需要顺序排序,那么您已经将它放在列表中元组的位置:

sorted_list = sorted(round_test, reverse =True)
# [(90L, 70L, 0L), (25L, 78L, 0L), (17L, 1L, 0L)]
ranked_list = []
for position, row in enumerate(sorted_list):
    ranked_list.append(tuple(row[0:2] + [position])) # replaces the 3rd row member
# ranked_list
# [(90L, 70L, 1), (25L, 78L, 2), (17L, 1L, 3)]