3

I have two arrays x and y:

x = [2 3 1 1 2 5 7 3 6]
y = [0 0 4 2 4 5 8 4 5 6 7 0 5 3 2 8 1 3 1 0 4 2 4 5 4 4 5 6 7 0]

I want to create a list "z" and want to store group/chunks of numbers from y into z and the size of groups is defined by the values of x.

so z store numbers as

z = [[0,0],[4,2,4],[5],[8],[4,5],[6,7,0,5,3],[2,8,1,3,1,0,4],[2,4,5],[4,4,5,6,7,0]]

I tried this loop:

h=[]
for j in x:
    h=[[a] for i in range(j) for a in y[i:i+1]]

But it is only storing for last value of x. Also I am not sure whether the title of this question is appropriate for this problem. Anyone can edit if it is confusing. Thank you so much.

傅能杰
  • 105
  • 1
  • 11
  • You need to append to `h`, not reassign it each time through the loop. – Barmar Jun 23 '21 at 05:25
  • Those are lists, not arrays. – Barmar Jun 23 '21 at 05:26
  • h=[h.append(x) for i in range(j) for x in X[i:i+1]] @Barmar like this? – 傅能杰 Jun 23 '21 at 05:26
  • No. `for j in x: h.append(...)` – Barmar Jun 23 '21 at 05:27
  • array as in numpy.ndarray or the module array? or are you talking lists and just call them array? you are missing delimiting , between your numbers in that case. if you use numpy, tag the question as such. – Patrick Artner Jun 23 '21 at 05:34
  • The Dupe [how-to-split-or-break-a-python-list-into-unequal-chunks-with-specified-chunk-si](https://stackoverflow.com/questions/47640407/how-to-split-or-break-a-python-list-into-unequal-chunks-with-specified-chunk-si) tells you how to solve it, the other one is one of many examples that dupe the error you did - recreating the list _inside_ the loop on every iteration. – Patrick Artner Jun 23 '21 at 05:40

2 Answers2

2

You're reassigning h each time through the loop, so it ends up with just the last iteration's assignment.

You should append to it, not assign it.

start = 0
for j in x:
    h.append(y[start:start+j])
    start += j
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Another way to do it would be by using (and consuming as you do) an iterator like so:

x = [2, 3, 1, 1, 2, 5, 7, 3, 6]
y = [0, 0, 4, 2, 4, 5, 8, 4, 5, 6, 7, 0, 5, 3, 2, 8, 1, 3, 1, 0, 4, 2, 4, 5, 4, 4, 5, 6, 7, 0]

yi = iter(y)

res = [[next(yi) for _ in range(i)] for i in x]
print(res)  # -> [[0, 0], [4, 2, 4], [5], [8], [4, 5], [6, 7, 0, 5, 3], [2, 8, 1, 3, 1, 0, 4], [2, 4, 5], [4, 4, 5, 6, 7, 0]]

Aside of the problem you are facing, and as a general rule to live by, try to give more meaningful names to your variables.

Ma0
  • 15,057
  • 4
  • 35
  • 65