zoukankan      html  css  js  c++  java
  • Python数组构造的坑

    今天写Python代码的时候遇到了一个大坑
    问题是这样的,我需要创建一个二维数组,如下:

    m = n = 3
    test = [[0] * m] * n
    print("test =", test)
    

    输出结果如下:

    test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    

    是不是看起来没有一点问题?
    一开始我也是这么觉得的,以为是我其他地方用错了什么函数,结果这么一试:

    m = n = 3
    test = [[0] * m] * n
    print("test =", test)
    
    test[0][0] = 233
    print("test =", test)
    

    输出结果如下:

    test = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    test = [[233, 0, 0], [233, 0, 0], [233, 0, 0]]
    

    是不是很惊讶?!
    这个问题真的是折磨,去网上一搜,官方文档中给出的说明是这样的:

    Note also that the copies are shallow; nested structures are not
    copied. This often haunts new Python programmers; consider:

    lists = [[]] * 3 lists [[], [], []] lists[0].append(3) lists [[3],
    [3], [3]] What has happened is that [[]] is a one-element list
    containing an empty list, so all three elements of [[]] * 3 are
    (pointers to) this single empty list. Modifying any of the elements of
    lists modifies this single list. You can create a list of different
    lists this way:

    lists = [[] for i in range(3)] lists[0].append(3)
    lists[1].append(5) lists[2].append(7) lists [[3], [5], [7]]

    也就是说matrix = [array] * 3操作中,只是创建3个指向array的引用,所以一旦array改变,matrix中3个list也会随之改变。

    建议使用列表生成式来构造list

  • 相关阅读:
    开发一个delphi写的桌面图标管理代码
    web颜色转换为delphi
    delphi RGB与TColor的转换
    用Delphi制作仿每行带按钮的列表
    Delphi 之 编辑框控件(TEdit)
    numEdit
    DropDownList添加客户端下拉事件操作
    19个必须知道的Visual Studio快捷键
    asp.net线程批量导入数据时通过ajax获取执行状态
    详解JQuery Ajax 在asp.net中使用总结
  • 原文地址:https://www.cnblogs.com/kuronekonano/p/11794293.html
Copyright © 2011-2022 走看看