简体   繁体   English

如何在 Python 中将数组声明为 function 参数?

[英]How to declare an array as a function parameter in Python?

I have declared an empty list.我已经声明了一个空列表。 I want to store in that one some strings from a text file.我想在其中存储一些来自文本文件的字符串。 If I am doing without creating TXT_to_PList it is working smoothly.如果我没有创建TXT_to_PList它工作顺利。 But using TXT_to_PList length of deTrimis array will be 0 .但是使用deTrimis数组的TXT_to_PList长度将为0 Why?为什么?

deTrimis = []

def TXT_to_PList(fileName,array):
    with open(fileName) as f:
        array = f.read().splitlines()
TXT_to_PList('strings.txt',deTrimis)
print (len(deTrimis))

You don't need that empty list at all:你根本不需要那个空列表:

def TXT_to_PList(fileName):
    with open(fileName) as f:
        return f.read().splitlines()

deTrimis = TXT_to_PList('strings.txt')

You can't modify function argument by assignment, change it to:您不能通过赋值修改 function 参数,将其更改为:

array.extend(f.read().splitlines())

see more info here: Why can a function modify some arguments as perceived by the caller, but not others?在此处查看更多信息: 为什么 function 可以修改调用者感知的某些 arguments,但不能修改其他人?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM