-1

顺序无关紧要,如何删除一个值,直到所有值都为空?它还会引发不存在任何价值的异常

例如:

d = {'a':1,'b':2,'c':1,'d':3}
remove a : {'b':2,'c':1,'d':3}
remove b : {'b':1,'c':1,'d':3}  
remove b : {'c':1,'d':3}
remove c : {'d':3}
remove d : {'d':2}
remove d : {'d':1}
remove d : {}
ValueError: d.remove(a): not in d
4

3 回答 3

3
d = {'a':1,'b':2,'c':1,'d':3}

while True:
    try:
        k = next(iter(d))
        d[k] -= 1
        if d[k] <= 0: del d[k]
        print d
    except StopIteration:
        raise ValueError, "d.remove(a): not in d"

{'c': 1, 'b': 2, 'd': 3}
{'b': 2, 'd': 3}
{'b': 1, 'd': 3}
{'d': 3}
{'d': 2}
{'d': 1}
{}

Traceback (most recent call last):
  File "/home/jamylak/weaedwas.py", line 10, in <module>
    raise ValueError, "d.remove(a): not in d"
ValueError: d.remove(a): not in d
于 2013-06-01T02:03:09.177 回答
0
d = {'a':1,'b':2,'c':1,'d':3}
for key in list(d.keys()):
    while True:
        print(d)
        d[key] -= 1
        if not d[key]:
            d.pop(key)
            break
    if not d:
        raise ValueError('d.remove(a): not in d')

Ouput:

{'a': 1, 'c': 1, 'b': 2, 'd': 3}
{'c': 1, 'b': 2, 'd': 3}
{'b': 2, 'd': 3}
{'b': 1, 'd': 3}
{'d': 3}
{'d': 2}
{'d': 1}

ValueError: d.remove(a): not in d
于 2013-06-01T02:57:32.107 回答
-1

Simple:

d = {'a':1,'b':2,'c':1,'d':3}

# No exception is raised in this case, so no error handling is necessary.
for key in d:
    value = d.pop(key)
    # <do things with value>
于 2013-06-01T01:41:54.873 回答