为什么不对我的所有列表都运行此循环?

时间:2019-07-17 10:43:14

标签: python python-3.x list loops for-loop

我有一些循环,似乎在相同的值上重复了自己,而不是运行整个列表。

indices = [[74],[81, 82, 83, 84, 85, 86],[21, 22, 23, 24, 25],[79]...]
len(indices) = 800

d1 = [[[],[],[],[],[]]]*len(indices)

for i in np.linspace(0,len(indices)-1,len(indices),dtype=int):
    for k in np.linspace(0,4,5,dtype=int):
        a = indices[i]

        d1[i][k] = a
labels = []
labels = d1

我想要得到的是:

labels = [[[74],[74],[74],[74],[74]],[81, 82, 83, 84, 85, 86],[81, 82, 83, 84, 85, 86],[81, 82, 83, 84, 85, 86],[81, 82, 83, 84, 85, 86],[81, 82, 83, 84, 85, 86]],...]]] as to mach my features for applying a machine learning algorithm, which are also of the form:

features = [[[...],[...],[...],[...],[...]],[...],[...]...]]].

我的输出是[[[57,58],[57,58],[57,58],[57,58],[57,58]],  [[57,58],[57,58],[57,58],[57,58],[57,58]],...]]。

我也以相同的方式创建了功能,并且没有问题,例如:


d1 = [[[],[],[],[],[]]]*len(features)
for i in np.linspace(0,len(features)-1,len(features),dtype=int):
    for k in np.linspace(0,len(features[i])-1,len(features[i]),dtype=int):

        a = features[i][k].tolist()
        d1[i][k].append(a)
features = []
features = d1

它完美地创建了特征= [[[[],[],[],[],[]],[] ...]]]形式的特征,对索引形式的特征进行迭代

非常感谢您!

1 个答案:

答案 0 :(得分:3)

此行会给您带来麻烦,因为您多次克隆同一行:

[[[],[],[],[],[]]] * len(indices)

避免这种情况的正确方法是:

[[[],[],[],[],[]] for _ in range(len(indices))]