【问题标题】:Am I really mutating the list?我真的在改变列表吗?
【发布时间】:2018-07-19 11:47:45
【问题描述】:

假设给了我一份清单

lst1 = [1,2,3,4]
removed_item = lst1.pop()
lst1.append(removed_item)

我暂时更改了这些值,但在运行后我已将一切恢复正常。这是否考虑改变列表?

【问题讨论】:

  • 如果只想修改最后一个元素的值,可以lst1[-1]访问。
  • 是的,你是。如果有其他线程,这将导致数据竞争。
  • 好酷,谢谢
  • 你是在问 Python 是否有办法优化这些调用?
  • @AustinA 不,我只是不确定我是否真的理解 python 中突变的定义。

标签: python list mutation


【解决方案1】:

是的,因为您删除了一个项目(改变列表),然后重新附加它(再次改变列表...)。

【讨论】:

    【解决方案2】:

    列表是可变的,而字符串不是。运行这段代码,你会得到答案

    lst1 = [1,2,3,4]
    print(id(lst1))
    removed_item = lst1.pop()
    print(id(lst1))
    lst1.append(removed_item)
    print(id(lst1))
    
    str1 = "a string"
    print(id(str1))
    removed_item = str1[-1]
    str1 = str1[:-1]
    print(id(str1))
    str1 += removed_item
    print(id(str1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 2014-06-06
      • 2014-01-25
      • 2021-11-19
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多