1

I have some loop that seems to repeat itself over the same values instead of running a whole list I have.

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

What I am trying to get is:

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 = [[[...],[...],[...],[...],[...]],[...],[...]...]]].

My output is [[[57, 58], [57, 58], [57, 58], [57, 58], [57, 58]], [[57, 58], [57, 58], [57, 58], [57, 58], [57, 58]],...]]].

I also created the features the same way, and I had no problem, like:


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

It creates a features of the form features = [[[],[],[],[],[]],[]...]]] perfectly, iterating over features which is of the form of indices.

Thank you very much!

Taco22
  • 123
  • 10

1 Answers1

3

This line will give you trouble, you're cloning the same rows several times:

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

The proper way to avoid this is:

[[[],[],[],[],[]] for _ in range(len(indices))]
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • The thing is I first create a list of len 800 with 5 lists embedded in each list[i], which I after want to replace for the same value in each list[i][k] with k from 0 to 4. I did the same to create the features and I had no problem whatsoever, doing it like this: 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 – Taco22 Jul 17 '19 at 11:02
  • Oops sorry, I double checked with my features one and it is copying the same all over again, thanks! – Taco22 Jul 17 '19 at 11:13
  • LópezSure, I was just running the code again, it worked, thanks! – Taco22 Jul 17 '19 at 11:26