簡體   English   中英

function中的參數好像沒有效果?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM