繁体   English   中英

如何在python 3.7中修复“运行时错误:字典在迭代过程中更改了大小”

[英]how to fix “ runtime error :dictionary changed size during iteration ” in python 3.7

if __name__ == '__main__':

    students = {}

    for _ in range(int(input())):
        name = input()
        score = float(input())
        seq = {name: score}
        students.update(seq)
        a = min(students, key=students.get)

    for key, value in students.items():
        while a == min(students, key=students.get):
            del students[min(students, key=students.get)]

    print(students)

在上面的代码中,我想删除字典中的最小值元素。

我能够从字典中删除单个最小元素。 但是,如果字典中有多个相同的最低价值元素,我想删除所有这些最低价值元素。

您可以对students.values()使用min来获取最小值,

然后收集所有具有相同值的键,

然后将del用于所有这些键,如下所示:

if __name__ == '__main__':

    students = {}

    for _ in range(int(input())):
        name = input()
        score = float(input())
        seq = {name: score}
        students.update(seq)

    min_val = min(students.values())
    all_keys_with_min_val = [key for key, value in students.items() if value == min_val]

    for key in all_keys_with_min_val:
        del students[key]

    print(students)

最可靠的方法不是删除条目,而是创建没有它们的新dict 使用dict理解来过滤出所有得分最低的条目:

if __name__ == '__main__':
    students = {}
    for _ in range(int(input())):
        name = input()
        score = float(input())
        students[name] = score  # store directly without update
    min_score = min(students.values())  # calculate minimum only once

    students = {
        name: score for name, score in students.items()
        if score != min_score  # only keep students above minimum score
    }
    print(students)

如果要修改初始dict ,请创建一个单独的条目列表以进行迭代:

...
min_score = min(students.values())  # calculate minimum only once

min_score_students = [name for name, score in students.items() if score == min_score]
for student in min_score_students:
    del students[key]
print(students)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM