简体   繁体   English

Python从函数返回列表

[英]Python return list from function

I have a function that parses a file into a list. 我有一个将文件解析为列表的函数。 I'm trying to return that list so I can use it in other functions. 我正在尝试返回该列表,以便我可以在其他功能中使用它。

def splitNet():
    network = []
    for line in open("/home/tom/Dropbox/CN/Python/CW2/network.txt","r").readlines():
        line = line.replace("\r\n", "")
        line = string.split(line, ',')
        line = map(int, line)
        network.append(line)
    return network

When I try to print the list outside of the function (for debugging) I get this error: 当我尝试在函数外部打印列表(用于调试)时,我收到此错误:

NameError: name 'network' is not defined

Is there something simple I am doing wrong or is there a better way to pass variables between functions without using globals? 有什么简单的我做错了还是有更好的方法在函数之间传递变量而不使用全局变量?

Variables cannot be accessed outside the scope of a function they were defined in. 变量不能在它们定义的函数范围之外访问。

Simply do this: 只需这样做:

network = splitNet()
print network

I assume you are not assigning the returned value to a variable in scope. 我假设您没有将返回值分配给范围内的变量。

ie. 即。 you can't do 你不能这样做

splitNet()
print network

instead you would 相反,你会

network = splitNet()
print network

or for that matter 或者就此而言

my_returned_network_in_scope = splitNet()
print my_returned_network_in_scope

otherwise you could declare network outside of the splitNet function, and make it global, but that is not the recommended approach. 否则你可以在splitNet函数之外声明网络,并使其成为全局网络,但这不是推荐的方法。

The names of variables in a function are not visible outside, so you need to call your function like this: 函数中的变量名称在外部不可见,因此您需要像这样调用函数:

networks = splitNet()
print(networks)

A couple of other notes: 其他几点说明:

  • You may want to convert your function to an iterator, using yield . 您可能希望使用yield将函数转换为迭代器。
  • You don't need to call readlines ; 你不需要调用readlines ; the function itself is an iterator. 函数本身是一个迭代器。
  • Your function may be leaking the file handle. 您的功能可能是泄漏文件句柄。 Use the with statement. 使用with语句。
  • You can use str.split , which is more readable and easier to understand than string.split . 您可以使用str.split ,它比string.split更易读,更易于理解。
  • Your file looks to be a CSV file. 您的文件看起来像是一个CSV文件。 Use the csv module . 使用csv模块

In summary, this is how your code should look like: 总之,这是您的代码应如下所示:

import csv
def splitNet():
    with open("/home/tom/Dropbox/CN/Python/CW2/network.txt") as nf:
        for line in csv.reader(nf, delimiter=','):
            yield map(int, line)
network = list(splitNet())
print (network)

Your function is returning a list so you have to assign it to a variable and than try to print it. 您的函数返回一个列表,因此您必须将其分配给变量,而不是尝试打印它。

network = splitNet()
print network

For example 例如

>>> def mylist():
...    myl = []
...    myl.append('1')
...    return myl
...
>>> my_list = mylist()
>>> my_list
['1']
>>>

Have you actually called the function yet? 你真的打电话给这个功能吗? This works fine (in the Python interpreter) 这工作正常(在Python解释器中)

 >>> def f():
 ...   network = []
 ...   network.append(1)
 ...   network.append(2)
 ...   network.append(3)
 ...   return network
 ...
 >>> network = f()
 >>> print network
 [1, 2, 3]
L=[1, 2, 3]

def rl(l): 
    return l

[*ll] = rl(L) # ll is in a list

ll
# >>> [1, 2, 3]

*t, = rl(L)   # ll is in a tuple

t
# >>> [1, 2, 3]

You may declare the name of the variable assigned to the list as global , like this: 您可以将分配给列表的变量的名称声明为global ,如下所示:

def get_list():
    global destination_list
    destination_list = []
    destination_list.extend(('1','2','3'))
    return destination_list

get_list()
print(destination_list)

If you want to return an item or list from a definition, you could define it before hand and use it as a variable during the initial writing of said definition. 如果要从定义中返回项目或列表,可以事先定义它并在初始写入所述定义期间将其用作变量。 Unless it has to be defined within the definition. 除非必须在定义中定义。 In this case you won't need to write in a return command at the end. 在这种情况下,您不需要在结尾处写入返回命令。

network = []

def splitNet(network):
    for line in open("/home/tom/Dropbox/CN/Python/CW2/network.txt","r").readlines():
        line = line.replace("\r\n", "")
        line = string.split(line, ',')
        line = map(int, line)
        network.append(line)

print network # Will print the list you've appended. But it is now a usable object. 
L=[1,2,3]
def rl(l): return l

[*ll]=rl(L) #ll is in a list
ll

Out[45]: [1, 2, 3] 出[45]:[1,2,3]

*t,=rl(L) #ll is in a tuple
t

Out[47]: [1, 2, 3] 出[47]:[1,2,3]

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

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