Can't resolve outer reference to global variable because of inner reference

时间:2018-04-18 18:01:59

标签: python flask

I Have the following code:

    l_sortedQueue = sorted(l_queue, key=lambda i: i['priority'])

    for i, d in enumerate(l_sortedQueue):
        if d['key'] == some_value:
            l_queue= l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i))

So I'm basically trying to move one of the dictionary entries in l_queue into a new index while shifting all the other values over one but because of how the data is organized in the list, I had to do it this way (sorting the list based on a 'priority' value before moving the item to a new index). For some reason however, when I reference l_queue within the for loop as in this line:

l_queue = l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i))

The OUTER reference to l_queue becomes unresolved, and the inner reference refers to a new local variable instead of the global list variable. Without this inner reference, it properly references the global variable however. Why is this? How do I get the inner and outer reference to l_queue to reference the global list variable?

Not sure if it is relevant, but this code comes from a flask function.

1 个答案:

答案 0 :(得分:1)

尝试打印此行:l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i))。您将看到它打印到None。这是因为insert是一个函数,它不会返回一个值。因此,您认为自己正在做的是将l_SortedQueue分配给l_queue,但您实际所做的是使用l_queue覆盖您的None列表。

您应将其更改为:

sortedQueue.insert(n_location, sortedQueue.pop())
que = sortedQueue

然而,看起来你以一种非常黑客的方式循环,我并没有真正关注。我认为除了这个解决方案之外,还有更好的解决方案。