我这样做是为了对得分较高的列表进行排序:
with open("scores.csv", "r") as x:
reader = csv.DictReader(x)
scores = [] # Makes an empty listto store the scores
for row in reader:
scores.append([row["Name"], row["Score"]])
# Sorts the list by score
scores.sort(reverse=True, key=lambda x: x[1])
但这是输出:
[['AnotherUser', '3'], ['James', '15'], ['James', '13'], ['User2', '12'], ['James', '0']]
显然,结果应该是这样:
[['James', '15'], ['James', '13'], ['User2', '12'], ['AnotherUser', '3'], ['James', '0']]
我在做什么错?在此先感谢:)
答案 0 :(得分:5)
最后一行应该是:
scores.sort(reverse=True, key=lambda x: int(x[1]))
代替:
scores.sort(reverse=True, key=lambda x: x[1])
因为字符串比较非常困难,所以您知道:-)
所以比较整数。