PYTHON3字典-为什么第一个答案不正确而第二个答案正确

时间:2020-03-26 07:50:21

标签: python sorting dictionary cts

在这两种情况下,我的第一个结果都不正确,而我的第二个结果正确。 有人可以向我解释其背后的原因吗?

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

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

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

预先感谢

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("\n\nDICTIONARY ASCENDING SORTED BY VALUE AND THEN BY KEYS ALBHABETICALLY DESCENDING FOR SAME VALUES")


print("InCorrect Answer- ",ValAscKeyDescDictionary1)
print("Correct Answer- ",ValAscKeyDescDictionary2)

print("--------------------------------------------------------------------------------")

print("\n\nDICTIONARY DESCENDING SORTED BY VALUE AND THEN BY KEYS ALBHABETICALLY DESCENDING FOR SAME VALUES")

print("InCorrect Answer- ",ValDescKeyDescDictionary1)
print("Correct Answer- ",ValDescKeyDescDictionary2)

print("--------------------------------------------------------------------------------")

1 个答案:

答案 0 :(得分:0)

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

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

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

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

因此,逻辑上的缺陷是无法通过将字符串乘以减一来反转字符串排序顺序。取而代之的是,您必须按它们与“最大”值的差异进行排序才能获得降序。

就您而言,如this answer

所述,您自己编写比较器可能更清晰
相关问题