【问题标题】:Python assignment operator: Right operand is also modified when Left operand is modified [duplicate]Python赋值运算符:修改左操作数时也修改右操作数[重复]
【发布时间】:2015-04-06 07:32:36
【问题描述】:

我正在做这个简单的事情,但我不希望在我修改左操作数(bananas)时修改右操作数(apples)。

>> apples = [1,2,3,4,5]
>> bananas = apples
>> bananas.remove(3)
>> bananas 
   [1,2,4,5]
>> apples 
   [1,2,4,5]

apples 应该是 [1,2,3,4,5] 而不是 [1,2,4,5]

请对此发表评论。

问候。

【问题讨论】:

标签: python variable-assignment


【解决方案1】:

避免使用它的最简单方法:

bananas = []+apples

【讨论】:

  • 复制列表,通常使用bananas = apples[:]
  • 要复制可能包含嵌入引用的列表,请使用bananas = copy.deepcopy(apples)
猜你喜欢
  • 2021-10-22
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
相关资源
最近更新 更多