如何修复此排序错误?

时间:2015-06-09 11:51:33

标签: python sorting python-3.x

我目前有下面的代码,但由于某种原因,它只使用数组中的第一个数字进行排序,例如,如果数字为1000,并且将其与50进行比较,则50将大于1000.我如何解决这个问题?

#!/usr/local/bin/python3.4
import operator
import pygame, sys
from pygame.locals import *
import random

placement = [1, 2, 3, 4, 5]
data = [
    {"score": "1000", "grade": "E", "music": "song5", "maxcombo": "1", "perfect": "20", "great": "1", "good": "20", "miss": "1"},
    {"score": "200", "grade": "D", "music": "song4", "maxcombo": "2", "perfect": "20", "great": "2", "good": "20", "miss": "2"},
    {"score": "500", "grade": "C", "music": "song3", "maxcombo": "3", "perfect": "20", "great": "3", "good": "20", "miss": "3"},
    {"score": "400", "grade": "B", "music": "song2", "maxcombo": "4", "perfect": "20", "great": "4", "good": "20", "miss": "4"},
    {"score": "300", "grade": "A", "music": "song1", "maxcombo": "5", "perfect": "20", "great": "5", "good": "20", "miss": "5"},
]

print (sorted(data, key=operator.itemgetter("score"), reverse=True))

1 个答案:

答案 0 :(得分:0)

“1000”不是数字。它是一个字符串,其字符恰好是数字。如果要按数字排序,请用数字表示数据。

data = [
    {"score": 1000, "grade": "E", "music": "song5", "maxcombo": 1, "perfect": 20, "great": 1, "good": 20, "miss": 1},
    #... etc

或者,如果由于某种原因必须将它们保留为字符串,请在键函数中转换为整数。

print (sorted(data, key=lambda row: int(row["score"]), reverse=True))