【问题标题】:Why isn't the value of list passed in a function getting updated?为什么在函数中传递的列表的值没有得到更新?
【发布时间】:2020-02-10 17:54:52
【问题描述】:
def mystery(l):
  l = l[0:5] #<-problem here
  return()

list1 = [44,71,12,8,23,17,16]
mystery(list1)

当我打印 list1 时,答案是 [44,71,12,8,17,16]。为什么 list1 没有在 l=l[0:5] 行更新,因为列表是可变的?

【问题讨论】:

    标签: python-3.x list function


    【解决方案1】:

    l 是一个局部变量;分配给一个名称永远不会改变它曾经引用的对象。如果要截断l 引用的列表,则需要使用类似

    l[:] = l[0:5]  # Replace the contents of the list with just the first 5
    

    或者更简单

    del l[5:]  # Remove all but the first 5 elements
    

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 2020-08-20
      相关资源
      最近更新 更多