Python遍历字典清空它



我有一些代码我正在分析。但是我发现在字典上迭代会清空它。我通过对字典进行深度拷贝并在一些显示值的代码中对其进行迭代来解决这个问题,然后使用原始字典对其进行迭代以将值分配给2D数组。为什么要对原始字典进行迭代以将其显示为空,这样以后使用字典就无法使用了,因为它现在是空的?欢迎回复。

import copy
# This line fixed the problem
trans = copy.deepcopy(transitions)
print ("nTransistions  = ")
# Original line was:
#  for state, next_states in transitions.items():
# Which empties the dictionary, so not usable after that
for state, next_states in trans.items():
    for i in next_states:
        print("nstate = ", state, " next_state = ", i)
# Later code which with original for loop showed empty dictionary
for state, next_states in transitions.items():
    for next_state in next_states:
        print("n one_step trans  state = ", state, " next_state = ", next_state)
        one_step[state,next_state] += 1

字典的打印版:

Transistions  = 
{0: <map object at 0x0000000003391550>, 1: <map object at 0x00000000033911D0>, 2: <map object at 0x0000000003391400>, 3: <map object at 0x00000000033915F8>, 4: <map object at 0x0000000003391320>}
类型:

Transistions  = 
<class 'dict'>
编辑:这是使用map的代码。关于如何编辑它来创建字典而不使用地图的任何建议?
numbers = dict((state_set, n) for n, state_set in enumerate(sets))
transitions = {}
for state_set, next_sets in state_set_transitions.items():
    dstate = numbers[state_set]
    transitions[dstate] = map(numbers.get, next_sets)   

在字典上迭代并不清空它。在map迭代器上迭代将清空该映射器。

无论您在哪里生成transitions字典,您都应该使用列表推导而不是map来为值创建列表而不是迭代器:

[whatever for x in thing]
不是

map(lambda x: whatever, thing)

最新更新