繁体   English   中英

Python 有没有类似于 Java 的 System.arraycopy 的东西?

[英]Does Python have anything like Java's System.arraycopy?

Python 有没有类似于 Java 的 System.arraycopy 的东西? 我不想只复制引用(浅拷贝),也不想切片(深拷贝 w/new ref)。 我想保留目标的引用(因为我有多个变量指向同一个列表)并将单个单元格从源复制到目标。 就像Java的arraycopy一样。 到目前为止,我能找到的在 Python 中做到这一点的唯一方法是编写我自己的。 在 Java 中,使用 System.arraycopy 比滚动自己的性能更高,不确定 Python 中是否如此。

如果我遵循所描述的行为,切片分配是执行此操作的 Pythonic 方式:

foo = range(10)
bar = foo
baz = range(10, 0, -1)
foo[0:4] = baz[0:4]

>>> foo
[10, 9, 8, 7, 4, 5, 6, 7, 8, 9]
>>> bar
[10, 9, 8, 7, 4, 5, 6, 7, 8, 9]

如果源包含对象引用,则会将相同对象的引用分配到目标中 - 如果您想深度复制源数据,我认为您必须执行以下操作:

foo[0:4] = [copy.deepcopy(x) for x in baz[0:4]]

更新: Peter DeGlopper 的方法更好。 去那个。

对不起,这是你得到的最好的:

def arrayCopy(src, srcPos, dest, destPos, length):
    for i in range(length):
        dest[i + destPos] = src[i + srcPos]
def array_copy(src: bytes, src_pos: int, dest: bytes, dest_pos: int, length: int) -> bytes:
return dest[:dest_pos]+src[src_pos:length]+dest[dest_pos+length:]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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