【问题标题】:variable error in function while assignment赋值时函数中的变量错误
【发布时间】:2020-01-12 10:24:55
【问题描述】:

编写 Python 脚本以按值对字典进行排序(升序和降序)

def sort_dictionary_ascending(dict):
    flag = True
    list = []
    while(len(dict)!=1):
        flag = True
        for x,y in dict.items():
            if flag:
                min = x
                flag = False
            elif min>x:
                min =x;
        list.append(min)
        dict.pop(min)
    min,value= dict.popitem()
    list.append(min)
    print(list)
def sort_dictionary_descending(dict):
    flag = True
    list = []
    while(len(dict)!=1):
        flag = True
        for x,y in dict.items():
            if flag:
                max = x
                flag = False
            elif max < x:
                max = x
        list.append(max)
        dict.pop(max)
    max,value= dict.popitem()
    list.append(max)
    print(list)
d = {1: 1, 3: 3, 4: 4, 2: 2, 5: 5}
sort_dictionary_descending(d)
sort_dictionary_ascending(d)

错误是:

/home/admin2/Desktop/two/venv/bin/python /home/admin2/Desktop/two/sort_dictionary.py
Traceback (most recent call last):
  File "/home/admin2/Desktop/two/sort_dictionary.py", line 45, in <module>
    sort_dictionary_ascending(d)
  File "/home/admin2/Desktop/two/sort_dictionary.py", line 17, in sort_dictionary_ascending
    list.append(min)
UnboundLocalError: local variable 'min' referenced before assignment
[5, 4, 3, 2, 1]

【问题讨论】:

  • 对字典进行排序的方法要简单得多。
  • 您在第一次调用sort_dictionary_descending(d) 时清空了原始字典d,因此当您调用sort_dictionary_ascending(d) 时,while(len(dict)!=1): 永远不会执行,min 永远不会被定义。请注意,您选择的变量名非常糟糕:您不应该使用 Python 内置函数的名称作为变量名,这会影响原始函数(dict、list、min、max...)
  • 不要使用dict作为变量或参数名,因为它是一个内置类型。

标签: python sorting dictionary


【解决方案1】:

首先在你的 for 循环中使用 for x in dict.keys() 而不是 for x, y in dict.items() 因为y 变量没有在整个循环中使用。其次,我不明白你为什么使用键等于值的字典,列表更合适

【讨论】:

  • 我必须在不使用内置函数的情况下对字典进行排序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 2018-07-08
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 2013-11-27
相关资源
最近更新 更多