[英]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. 但是,这并不十分Python化-就我所知,列表理解通常更喜欢循环,即使我在搜索的几个小时内都没有找到它,也可能有一些函数可以更优雅地实现这一点。 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. 编辑:我也对NumPy解决方案感兴趣,甚至比普通的Python感兴趣。
You can replace the inner loop with slice-replacement: 您可以将内部循环替换为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: 根据您要执行的操作,可以使用
numpy
-arrays作为替代方案:
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 . 您现在正在做的事情似乎是错误的,首先要从
start[0]
和start[1]
开始i
和j
,但是在分配值时,您要再次添加start[0]
和start[1]
。 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. 在我看来,这似乎是pythonic的,尝试使用列表理解来做到这一点将使其变得不可读,对我而言,这不是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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.