【问题标题】:Bug? is remove() supposed to remove from associated lists? [duplicate]漏洞? remove() 应该从关联列表中删除吗? [复制]
【发布时间】:2021-01-19 16:50:13
【问题描述】:

设置第二个列表等于第一个列表

first_lzt = ['room', 'floor', 'name']
second_lzt = first_lzt

remove() 来自第二个列表的元素。

second_lzt.remove('room')

令人惊讶的是,该元素也从第一个列表中删除。为什么?

>>> first_lzt

['floor', 'name']

这应该发生吗?如何使second_lzt 独立而不向其中添加项目?

Python 3.7.6


编辑:预期的对象行为。

str1 = "apple"
str2 = str1
str2 = str2 + "_pie"

>>> str1
"apple"
int1 = 3
int2 = int1
int2 += 4

>>> int1
3

【问题讨论】:

  • 分配不复制列表。您只有一个列表对象,其中有 2 个名称指向它。
  • 这能回答你的问题吗? Python modifying wrong list?
  • 字符串是不可变的——你永远不能改变它们
  • @juanpa.arrivillaga OP 发布了一个带有字符串的示例
  • @HashRocketSyntax 在整个语言中是完全一致的。它也是大多数相似语言的完全相同的语义,例如Java, JS, Ruby 等等 你有 C 背景吗? C 和 C++ 的工作方式不同。

标签: python python-3.x list


【解决方案1】:

要使列表独立,请使用.copy。例如:

first_lzt = ['room', 'floor', 'name']
second_lzt = first_lzt.copy()

现在,如果您执行second_lzt.remove("room"),它将从第二个列表中删除空间。

【讨论】:

    【解决方案2】:

    是的,它不会在后台创建第二个列表,就像@Chase 说您正在将一个变量引用到列表中。仅此而已。

    #使用切片语法复制列表

    first_lzt = ['room', 'floor', 'name']
    second_lzt = first_lzt[:]
    

    watch your code in action

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2020-12-26
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多