zoukankan      html  css  js  c++  java
  • python中的list的*运算使用过程中遇到的问题

    目的:

    想生成一个[[],[],[]] 这样的列表,

    所以就 [[]]*3 这样做了,但是这样做会有问题,这样list中的三个list其实是同一个list。

    例如:a=[[]]*3,然后a[0].append(1),

    然后a就变成这样了:[[1],[1],[1]]

    验证一下,发现表达式 a[0] is a[1] 的值为True。

    如何解决呢,可以用列表生成器:a=[[] for i in range(3)]

    这应该像是值类型和引用类型的区别,但是翻看python的文档时没发现有类似的说法,不过在翻看文档时发现里面提到了这个情形:

    https://docs.python.org/3.6/library/stdtypes.html

    内容摘录如下:

    Note that items in the sequence s are not copied; they are referenced multiple times. 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 references 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]]
    
  • 相关阅读:
    cv2.imwrite()指定图片存储路径问题
    fgets读取文件最后一行重复问题
    KEAZ128 时钟配置
    MinGW x64 for Windows安装
    [python] pygame安装与配置
    S32K144之时钟配置
    C/C++ scanf和gets 区别 , printf和puts区别
    堆排序
    约瑟夫问题
    Coursera 国内无法登陆问题
  • 原文地址:https://www.cnblogs.com/vanwoos/p/9217130.html
Copyright © 2011-2022 走看看