正在尝试对已排序词典执行.reverse(),但得到“None”

2024-10-04 03:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对从a文件加载的词典进行排序,但是反向排序时得到“无”,我已经寻找了可能的解决方案,但似乎找不到任何东西,这可能是愚蠢的事情,但任何帮助都将不胜感激:)

(我用它来尝试反向排序: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())

Tags: pathimportdictionary排序osdirnpoperator
1条回答
网友
1楼 · 发布于 2024-10-04 03:28:35

反作用到位

>>> a=[1,2,3]
>>> a
[1, 2, 3]
>>> a.reverse()
>>> a
[3, 2, 1]

在未绑定的临时对象上调用reverse是无用的;)。您需要绑定它:

>>> b=sorted(a)
>>> b.reverse()
>>> b
[3, 2, 1]

相关问题 更多 >