嵌套循环中使用字典的奇怪赋值行为

时间:2017-10-25 15:33:03

标签: python dictionary for-loop variable-assignment

所以我需要在字典中重新排列一些值。具体来说,对于' Verb',该列表出现在' verb three'之前,我希望它能在之后出现。我试图在虚拟列表上使用foo[i], foo[j] = foo[j], foo[i]交换方法,然后我将分配原始列表。像这样:

test_dict = {'Noun': ['noun one', 'noun two', 'noun three'], 
             'Verb': ['verb one', 'verb two', ['list one', 'list two',
                      'list three'], 'verb three', 'verb four']}

e = test_dict

for key in sorted(e):
    fixed_list = e[key]
    print('    ', key)
    for i in range(0, len(e[key])):
        print(i)
        print(type(e[key][i]))    
        if type(e[key][i]) == list:  
            print('ooh, this one\'s a list!', e[key][i])
            print('   and here it is in fixed_list: ', fixed_list[i])
            fixed_list[i], fixed_list[i+1] = fixed_list[i+1], fixed_list[i]
    e[key] = fixed_list

然而,我得到的奇怪输出是[注意:我的' Verb' key 永远不会到最后,所以忽略IndexError]:

 Noun
0
<class 'str'>
1
<class 'str'>
2
<class 'str'>

 Verb
0
<class 'str'>
1
<class 'str'>
2
<class 'list'>
ooh, this one's a list! ['list one', 'list two', 'list three']
and here it is in fixed_list:  ['list one', 'list two', 'list three']
3
<class 'list'>
ooh, this one's a list! ['list one', 'list two', 'list three']
and here it is in fixed_list:  ['list one', 'list two', 'list three']
4
<class 'list'>
ooh, this one's a list! ['list one', 'list two', 'list three']
and here it is in fixed_list:  ['list one', 'list two', 'list three']
Traceback (most recent call last):
File "/home/ubuntu/workspace/my_project.py", line 567, in <module>
fixed_list[i], fixed_list[i+1] = fixed_list[i+1], fixed_list[i]
IndexError: list index out of range

现在,除非我疯了,似乎重新分配fixed_list的元素会导致内部循环内的键值列表出现问题,但是如何?他们唯一一次触摸&#39;彼此分配是在外循环的开始和结束。

0 个答案:

没有答案