Python 列表追加行为 [英] Python list append behavior

查看:32
本文介绍了Python 列表追加行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的不知道如何表述问题...

Don't really know how to formulate the question...

假设我执行以下操作:

    >>> l = [[]]*2
    >>> l
    [[], []]
    >>> l[0].append(1)
    >>> l
    [[1], [1]]

为什么 1 会附加到两个列表中?

Why does 1 gets appended to both lists?

推荐答案

[[]]*2 是对同一个列表的两个引用的列表.您附加到它然后看到它两次.

[[]]*2 is a list of two references to the same list. You are appending to it and then seeing it twice.

这篇关于Python 列表追加行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆