Pythonic策略覆盖for循环中的全局变量

时间:2014-04-19 11:33:31

标签: python for-loop numpy

EDIT2:

感谢您的帮助,问题解决了,采用了中间方法:

enter image description here

当它有资格被接受时会接受答案!


编辑:

我被问到更简单的变量,好吧,我会尝试:)

假设我希望将数据放在单独的变量abcd中,如何在for循环中为它们分配数据?< / p>

这样的方法:

a, b, c, d = [], [], [], []

for var,data in zip([a,b,c,d], some_data_array):
    var = #data that comes from some operation on data array

不起作用,变量a, b, c, d仍然是[],因为它们属于全局范围。


我有一个训练数据集train_set(numpy数组),我希望将其缩减为较小的训练数据集(90%,80%,70%等)。 我不想复制&amp;粘贴程序

train_90perc = train_set[np.random.choice(train_set.shape[0],\
        train_set.shape[0] * 0.9, replace=False),:]

并认为我可以用for循环来做。但是怎么样?我的初始方法(下面)有一个问题,即它不会修改全局范围内的变量。因此,当我在for循环之后打印例如train_80perc时,它仍然是[]。 PS:前两行是初始化变量,还有一种方法可以解决这个问题(因为它看起来很难看)。

train_100perc, train_90perc, train_80perc, train_70perc, train_60perc, train_50perc,\
train_40perc, train_30perc, train_20perc, train_10perc = [], [], [], [], [], [], [], [], [], []

for train,size in zip([train_100perc, train_90perc, train_80perc,\
                       train_70perc, train_60perc, train_50perc,\
                       train_40perc, train_30perc, train_20perc, train_10perc],\
                       [p for p in reversed([i/10 for i in range(1,11)])]
                     ):
    #global train
    train = train_set[np.random.choice(train_set.shape[0],\
    train_set.shape[0] * size, replace=False),:]

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

<强>更新

请勿将某些数据分配给var。因为它只是参考。

a, b, c, d = [], [], [], []

for var,data in zip([a,b,c,d], some_data_array):
    # call var.extend or var.append
    # var = some_value # don't do this. because it's just reference.
    var.extend(some_list)

您是否必须生成train_100perc ...?

我的建议是

subset = {}
for percent in np.arange(10, 100, 10):
    np.random.shuffle(train_set) # shuffle in-place
    subset[percent] = train_set[:len(train_set)*percent*0.01].copy() # selection of training data

np.arange(10, 100, 10)可能会有所不同。