-1

I am wondering if I can replace values of a list of lists with values of another list in Python:

let's say

W = [[0,0],[0,0,0],[0,0,0,0,0]]

V = [1,2,3,4,5,6,7,8,9,10]

I am wondering if I can replace values of W with values of V, in such a way that it becomes like below:

W = [[1,2],[3,4,5],[6,7,8,9,10]]

Thanks a lot!

Baptiste Mille-Mathias
  • 2,144
  • 4
  • 31
  • 37
  • w = [[0, 0], [0, 0, 0], [0, 0, 0, 0, 0]] v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] z = 0 for i in w: x = 0 while x < len(i): i[x] = v[z] x += 1 z += 1 print(w) So sad this was a very fun question the setup and desire results were tricky, but this is a for loop to solve this, you will have to reformat it – vash_the_stampede Aug 31 '18 at 22:29

2 Answers2

4

You can use iter:

W = [[0,0],[0,0,0],[0,0,0,0,0]]
V = [1,2,3,4,5,6,7,8,9,10]
v = iter(V)
new_w = [[next(v) for _ in i] for i in W]

Output:

[[1, 2], [3, 4, 5], [6, 7, 8, 9, 10]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • While this makes sense and is the most concise solution, it seems like a waste to create an array of zeros only to throw it away in a subsequent operation. – cs95 Aug 31 '18 at 22:15
  • @coldspeed Unless the OP truly wishes to mutate `W` in place, it seems that the latter is being used purely to structure the final output. – Ajax1234 Aug 31 '18 at 23:43
1

Convert V into an iterator, slice with itertools.islice and assign back to W:

from itertools import islice
it = iter(V)
for i in W:
    i[:] = islice(it, len(i))

print (W)
[[1, 2], [3, 4, 5], [6, 7, 8, 9, 10]]

I like this because it updates W in place without creating a new list.

cs95
  • 379,657
  • 97
  • 704
  • 746