1

我在以下代码中遇到了 def load() 问题:

def load():
     claim = {}
     data = open("claim.DB").read().split("\n")
     for a in data:
          claimDB[a.split(",")[0]] = a.split(",")[1:]
     claim.claimDB = claimDB

出于某种原因,这条线在def load():

claimDB[a.split(",")[0]] = a.split(",")[1:]

导致此问题:

dictionary changed size during iteration

并且每次你做 claim.load() 时都让 dict 这样做:

{'': [], 'asl97': ['charles', 'donboricua'], 'a': ['s', 'l', '9', '7', 'c', 'h', 'a', 'r', 'l', 'e', 's']}

{'':[],'a':['s','','','l','','','9','','','7','',' ','c','','','h','','','a','','','r','','','l','',' ', 'e', '', '', 's']}

4

1 回答 1

0

如果您已经在claimDB外面迭代,就会发生这种情况load()。以下代码:

claimDB = dict(x=1)

def load():
    data ="1,2\n2,3".split("\n")
    for a in data:
        # modify claimDB <--- BAD
        claimDB[a.split(",")[0]] = a.split(",")[1:]

# iterate over claimDB <--- OK
for k in claimDB:
    load()

原因RuntimeError: dictionary changed size during iteration

假设是这种情况,您需要提取 的内容claimDB,然后对其进行循环:

# iterate over the contents of claimDB; it's safe to modify it now, 
# because .items() copies the contents for the generator; list() makes it python 3 safe.
for k, v in list(claimDB.items()):
    load()
于 2013-11-15T07:14:39.560 回答