How to make a copy of a 2D array in Python?

This question already has an answer here:

  • Copying nested lists in Python 2 answers
  • How to clone or copy a list? 17 answers

  • Try this:

    from copy import copy, deepcopy
    y = deepcopy(x)
    

    I'm not sure, maybe copy() is sufficient.


    Using deepcopy() or copy() is a good solution. For a simple 2D-array case

    y = [row[:] for row in x]
    

    对于二维数组,可以使用映射函数:

    old_array = [[2, 3], [4, 5]]
    # python2.*
    new_array = map(list, old_array)
    # python3.*
    new_array = list(map(list, old_array))
    
    链接地址: http://www.djcxy.com/p/4522.html

    上一篇: 带有负跨度的序列开始处的扩展切片

    下一篇: 如何在Python中制作二维数组的副本?