python-3.x - 为什么在函数中传递的 list 的值没有得到更新?
问题描述
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] 行更新,因为列表是可变的?
解决方案
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
推荐阅读
- django - 找不到 GDAL 库(尝试了“gdal202”、“gdal201”、“gdal20”、“gdal111”、“gdal110”、“gdal19”)
- azure - Get-MsolUserRole Azure AD V2 cmdlet 等效项
- javascript - 从 Date 中删除微秒并使用 toISOString() 进行转换
- python - Pandas Groupby Grouper,我如何对每个组都不存在的日期进行分组?
- javascript - 尝试设置 Travis,安装前中断
- excel - 无法使用 VBA 将带有数据的标题从 Access 拉到 Excel,
- excel - 更改图表系列公式和阻止图表激活
- matlab - 如何保存迭代编号。在matlab中按下按键
- php - Doctrine 实体总是在持久化时保存 null,即使在设置时也是如此
- angular - Angular 6 Mat-Dialog 隐藏了背景网页的一部分