我正在尝试对从一个文件加载的字典进行排序,但是当我反向排序时我得到'无',我已经寻找可能的解决方案但似乎无法找到任何东西,它可能是一些愚蠢的但是任何帮助将不胜感激:))
(我用这个作为反向排序的尝试:How to sort a dictionary by value?)
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
然后评论中有人说使用
sorted_x.reverse()
将返回排序后的结果,但首先是最大的数字......但事实并非如此......
这是我的代码,我试图尽可能多地取出不必要的东西
import os
from pathlib import Path
from random import randint
import numpy as np
import operator
debug = True
quizanddifficulty = "Maths,Easy"
score = 3
uinputuname = "Kieron"
# Get current operating File Path
dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path)
pathsplit = dir_path.split("\\")
newstring = ""
for string in pathsplit:
newstring = newstring + str(string) + "\\\\"
print(newstring)
currentpath = newstring
split = quizanddifficulty.split(",") # Split Quiz Type and Difficulty (Quiz = split[0] and difficulty = split[1])
quizfiledifficulty = split[0] + split[1] + ".npy" # Set file extension for the doc
overall = currentpath + "QUIZDATA" + "\\\\" + quizfiledifficulty # Set overall file path (NEA\QUIZDATA\{Quiz}.npy)
try:
# Load
dictionary = np.load(overall).item()
dictionary.update({score:uinputuname})
np.save(overall, dictionary)
except OSError:
# Save
if debug:
print(OSError)
print("File does not already exist, Creating!")
dictionary = {score:uinputuname}
np.save(overall, dictionary)
print(dictionary)
sorted_x = sorted(dictionary.items(), key=operator.itemgetter(0))
print(sorted_x.reverse())
答案 0 :(得分:0)
反向就地行动
>>> a=[1,2,3]
>>> a
[1, 2, 3]
>>> a.reverse()
>>> a
[3, 2, 1]
在非绑定的临时对象上调用reverse是没用的;)。你需要绑定它:
>>> b=sorted(a)
>>> b.reverse()
>>> b
[3, 2, 1]