簡體   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