[英]parameter in function seems to have no effect?
我使用 function 允许我将文件的数据写入列表,但我必须丢失一些东西,因为我的 function 中定义列表的参数似乎不起作用,你知道问题是什么吗? 有我的 function:
filePath = path + "\ONLYIVENOTFIXED.txt"
listObj = []
i = listObj
def writeFileOnAList(pathofThefile, namelist):
fichierIve = open(pathofThefile, "r")
namelist = fichierIve.readlines()
namelist = [x.strip() for x in namelist]
i = namelist
i = 0
writeFileOnAList(filePath, listObj)
print(listObj)
它告诉我 function 中的“名单”设置未使用,当我调用 function 并尝试打印我的列表时,它会打印一个空列表
你有什么解决办法?
关键问题是 Python 是传递对象引用语言,而不是传递变量引用:即 object 引用是按值传递的。 因此,分配给 function 中的 namelist 只会更改该变量的值:它对仍然引用原始列表的 listobj 没有任何影响。
解决此问题的最 Pythonic 方法是让 function 返回的名单:
filePath = path + "\ONLYIVENOTFIXED.txt"
def writeFileOnAList(pathofThefile):
with open(pathofThefile, "r") as ficiherIve:
namelist = fichierIve.readlines()
namelist = [x.strip() for x in namelist]
return namelist
listObj = writeFileOnAList(filePath)
您的脚本中确实有很多错误:
filePath = path + "\ONLYIVENOTFIXED.txt"
listObj = []
# You are declaring the variable "i" here but you are never using it
i = listObj
def writeFileOnAList(pathofThefile, namelist):
fichierIve = open(pathofThefile, "r")
# You are parsing your listObj as parameter (namelist) but you never use it
# instead you are just overwriting it
namelist = fichierIve.readlines()
namelist = [x.strip() for x in namelist]
# Here you are overwriting your i variable 2 times in a row and never work with it
# after that
i = namelist
i = 0
writeFileOnAList(filePath, listObj)
print(listObj)
我不确定你想做什么,但这是我的修改版本:
filePath = path + "\ONLYIVENOTFIXED.txt"
def writeFileOnAList(pathofThefile):
fichierIve = open(pathofThefile, "r")
namelist = fichierIve.readlines()
namelist = [x.strip() for x in namelist]
return namelist
listObj = writeFileOnAList(filePath)
print(listObj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.