python - 我的程序运行良好,但我不明白为什么?与函数和嵌套列表有关
问题描述
我试图用python制作一个程序来替换任意嵌套列表中的一个项目。要访问该项目,程序将使用索引列表,例如[3, 0, 1]
. 这将类似于访问嵌套列表(如list[3][0][1]
.
我有一个应该替换嵌套列表中的项目的函数。
def ReplaceItemInNestedList(nestedList, indexList, replacement):
for i in indexList[:-1]:
nestedList = nestedList[i]
lastIndex = indexList[-1]
nestedList[lastIndex] = replacement
像这样使用时它完美地工作。唯一的问题是我不明白为什么会这样:
myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6
ReplaceItemInNestedList(myNestedList, myIndexList, replacement)
myNestedList: [[0, 1], [6, 3]]
我不明白如何myNestedList
仍然是嵌套列表而不是常规列表。我希望更具体地说,它是一个物品将被替换的地方。那是因为 nestedList 在 for 循环运行时会反复重新定义,并从嵌套列表重新定义到其中的常规列表。
当我将函数放入我的代码中时,我得到了我理解的行为,但这不是我想要的。
myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6
for i in myIndexList[:-1]:
myNestedList = myNestedList[i]
lastIndex = myIndexList[-1]
myNestedList[lastIndex] = replacement
myNestedList: [6, 3]
理想情况下,我希望有class NestedList
一个self.value = [[0, 1], [2, 3]]
参数在调用 method 时会发生变化changeValueAtIndexList(indexList, replacement)
,但我真的似乎无法将当前的“神奇”解决方案放入一个类中。请帮助我了解我的程序发生了什么。
解决方案
我猜你的班级解决方案可能是这样的:
class NestedList:
def __init__(self, nestedlist):
self.value = nestedlist
def changeValueAtIndexList(self, indexList, replacement):
nestedList = self.value
for i in indexList[:-1]:
nestedList = nestedList[i]
lastIndex = indexList[-1]
nestedList[lastIndex] = replacement
#myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6
myNestedList = NestedList([[0, 1], [2, 3]])
myNestedList.changeValueAtIndexList(myIndexList, replacement)
myNestedList.value
# [[0, 1], [6, 3]]
“魔术”是函数或方法内的 nestedList 遍历列表,但方法中的 self.value 或第一个示例中函数外的 myNestedList 仍然指向原始列表。
推荐阅读
- angular - 如何获取多个联合接口类型的属性的值?
- sql - SQL SELECT ABS 值中最接近的行和每侧一个而不使用 UNION ALL
- performance - 一段时间不活动后,Nginx 静态文件服务缓慢
- proxy - 有没有办法仅基于邮递员环境应用代理配置?
- pandas - 如何根据列表值列的内容扩展数据框?
- object - Julia 的内部构造函数
- c++ - C++ 中循环的性能差异
- pine-script - 修改用于股票交易的 Pine 脚本
- parsing - 需要将 monard chainrl 转换为 applicative 风格
- javascript - 当按钮未定义时,“未捕获的类型错误:无法设置未定义的属性‘onclick’”