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]]
    
  • 相关阅读:
    phpcms v9模板制作常用代码集合
    phpcms v9模板制作教程
    cookie 和session 的区别
    PHP的加密方式
    php基础
    复习 语句
    empty 和 isset的区别和联系
    MySQL数据库引擎介绍、区别、创建和性能测试的深入分析
    ThinkPHP增删改查--改
    使用ajax提交form表单,包括ajax文件上传
  • 原文地址:https://www.cnblogs.com/vanwoos/p/9217130.html
Copyright © 2011-2022 走看看