简体   繁体   中英

Copying a list of lists into part of another one in the most pythonic way

I have a large list of lists, for now containing only zeros. I have another, smaller list of lists which I want to copy to certain positions in the bigger list of lists. I want to replace the original values. The only way I've found so far is this:

start = (startrow, startcol)

for i in range( start[0], start[0] + len(shortlist) ):
  for j in range( start[1], start[1] + len(shortlist[0]) ):
    longlist[i][j] = shortlist[i-start[0]][j-start[1]]

However, this doesn't feel very pythonic - as far as I know, list comprehensions are in general prefered to loops, and even though I didn't find it in few hours of searching, there might be some function doing this more elegantly. So is there some better solution than mine?

EDIT: I'm interested in NumPy solutions as well, or perhaps even more than in plain Python ones.

You can replace the inner loop with slice-replacement:

start = (startrow, startcol)

for i, elements in enumerate(shortlist, start[0]):
    longlist[i][start[1]:start[1] + len(elements)] = elements

Depending on what you want to do, using numpy -arrays could be an alternative:

large[startrow:startrow + small.shape[0], startcol:startcol + small.shape[1]] = small

What you are doing right now seems to be wrong, you are first starting i and j from start[0] and start[1] , but when assigning the values, you are adding start[0] and start[1] again . I do not think this is what you intended.

What you indented could be something like -

for i,x in enumerate(shortlist):
    for j,y in enumerate(x):
            longlist[i+start[0]][j+start[1]] = y

This seems pythonic enough to me, trying to do this with list comprehension would make it unreadable, which according to me is not pythonic.

Example/Demo -

>>> shortlist = [[1,2],[3,4]]
>>> longlist = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
>>> start = 1,1
>>> for i,x in enumerate(shortlist):
...     for j,y in enumerate(x):
...             longlist[i+start[0]][j+start[1]] = y
...
>>> longlist
[[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM