2014-10-30 46 views
0

我在使用dict理解時遇到了手動垃圾收集的限制。python 2.7:如何最好地刪除在詞典理解中引用的變量?

SyntaxError: can not delete variable 'first_dict' referenced in nested scope 

這並不與列表內涵發生了,既不用蟒蛇3.要解決這個問題,我可以,例如,使用:

def f(): 
    first_dict = {'a':4, 'b':2} 
    second_dict = {k:first_dict[k] for k in ['a']} 
    del first_dict 

在Python 2.7中運行時生成此for循環(慢),或者可能創建一個元組列表,並從那裏做我的字典?任何更好的想法?

編輯:這裏有幾個類似用途的情況下,@ JeffMercado的提示(在評論)將不起作用:

import numpy as np 
import gc 
def f(stuff): 
    # stuff is a dict of lists of array indices 

    # get a numpy array, perhaps from a db or via some convluted calculation. I'm using np.arange as a dummy 
    arr = np.arange(10) 

    # a problematic 'nested scope' indexing into arr 
    ret_1 = {k:arr[indices] for k,indices in stuff} 

    # another problematic 'nested scope' invoking a function 
    ret_2 = {k:cool_function(arr,v) for k,v in stuff} 

    # do some more calculations to generate other return values 
    other_ret = 'other return values' 

    # cleanup intermediary data to release memory for other processes 
    del arr 
    gc.collect(0) 

    return ret_1, ret_2, other_ret 

好了,你很可能做一些醜陋像{k:v for k,indicies in stuff for i,v in enumerate(arr) if i in indices}到在ret_1附近工作,但ret_2不太容易修復。

+0

這工作,但我不知道規則,足以解釋爲什麼這個工程在你原來的做法:'{ k:v for k,v in first_dict.iteritems()if k in ['a']}' – 2014-10-30 07:04:19

+0

它的工作原理是因爲這些值不直接引用first_dict。我的實際使用情況稍微複雜一點,選擇first_dict的元素將不起作用 - 我會稍微改變一下問題以反映這一點。道歉.. – drevicko 2014-10-30 23:51:30

+0

從頭開始!我只是嘗試過'{k:v for k,用於v中的東西的指示'},這沒有多大意義,但會產生語法錯誤!我必須承認它的邏輯超出了我。 – drevicko 2014-10-31 00:38:54

回答

0

下面是一個使用,似乎工作的元組列表的方法:

def f(): 
    first_dict = {'a':4, 'b':2} 
    second_dict = dict([(k,first_dict[k]) for k in ['a']]) 
    del first_dict 

這不是理想的,因爲它創建列表(這可能是大的,因此,將其刪除的慾望)。不幸的是,如果我用這樣一臺發電機:

def f(): 
    first_dict = {'a':4, 'b':2} 
    second_dict = dict((k,first_dict[k]) for k in ['a']) 
    del first_dict 

我仍然得到語法錯誤):