zoukankan      html  css  js  c++  java
  • 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]]

    参考文献: zhang
  • 相关阅读:
    smarty中ifelse、foreach以及获取数组中键值名的一个实例
    smarty逻辑运算符
    python strip()函数 介绍
    (转)论python工厂函数与内建函数
    数据结构哈希表(转)
    哈希表算法的编写
    哈希表(转)
    平衡二叉树的旋转操作
    并查集详解(转)
    Java数组技巧攻略
  • 原文地址:https://www.cnblogs.com/nxf-rabbit75/p/10070612.html
Copyright © 2011-2022 走看看