PYTHON3 DICTIONARY-为什么第一个答案不正确,而第二个答案正确



在这两种情况下,我的第一个结果都是不正确的,而我的第二个结果是正确的。谁能向我解释一下这背后的原因吗?

我的第一个要求是先按值升序排列字典,然后按键降序排列

我的第二个要求是先按值降序排列字典,然后按键降序排列

我试过一点,但陷入了两个对我不起作用的概念。我只是想知道这些逻辑不正确的原因。

提前感谢

from collections import OrderedDict
#Value Descending and then Key Ascending[Descending means -ve,Ascending means +ve]
def sorted_dict_by_firstValue_secondKey(dictionary,AscendingKey=True,AscendingValue=True,reverse=False):
Dictionary = OrderedDict()
keySign = 1
valSign = 1
if(AscendingKey==False):
keySign = -1
if(AscendingValue==False):
valSign = -1
for key,value in sorted(dictionary.items(),key=lambda item: (valSign*item[1],keySign*item[0]),reverse=reverse):
Dictionary[key] = value
return Dictionary

album = {'carl':40,'oswald':2,'bob':1,'danny':3,'alice':1,'alan':2,'tom':3,'alquaida':40, 'elizabeth':40}

ValAscKeyDescDictionary1 = sorted_dict_by_firstValue_secondKey(album,AscendingValue=True,AscendingKey=False)
ValAscKeyDescDictionary2 = sorted_dict_by_firstValue_secondKey(album,AscendingValue=False,AscendingKey=True,reverse=True)

ValDescKeyDescDictionary1 = sorted_dict_by_firstValue_secondKey(album,AscendingValue=False,AscendingKey=False)
ValDescKeyDescDictionary2 = sorted_dict_by_firstValue_secondKey(album,reverse=True)
print("--------------------------------------------------------------------------------")
print("nnDICTIONARY ASCENDING SORTED BY VALUE AND THEN BY KEYS ALBHABETICALLY DESCENDING FOR SAME VALUES")

print("InCorrect Answer- ",ValAscKeyDescDictionary1)
print("Correct Answer- ",ValAscKeyDescDictionary2)
print("--------------------------------------------------------------------------------")
print("nnDICTIONARY DESCENDING SORTED BY VALUE AND THEN BY KEYS ALBHABETICALLY DESCENDING FOR SAME VALUES")
print("InCorrect Answer- ",ValDescKeyDescDictionary1)
print("Correct Answer- ",ValDescKeyDescDictionary2)
print("--------------------------------------------------------------------------------")

观察:当您设置AscendingKey=False时,它无法正常工作。

这是因为在这种情况下,使用(valSign*item[1],-1*item[0])进行排序。item[0]是密钥,在您的情况下是一个字符串。

将负整数与字符串相乘似乎总是得到空字符串:

>>> -1*"hello"
''
>>> -2*"hello"
''
>>> 1*"hello"
'hello'
>>> 2*"hello"
'hellohello'

因此,逻辑中的缺陷在于,不能通过将字符串与负1相乘来反转字符串排序顺序。相反,您必须根据它们的差异排序到"最大"值,才能获得降序。

在你的情况下,自己写一个比较器可能更清楚,正如这个答案中所概述的那样

最新更新