函数的Python返回列表 [英] Python return list from function

查看:139
本文介绍了函数的Python返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将文件解析成列表的函数。我试图返回该列表,以便我可以在其他函数中使用它。

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

当我尝试在函数外面打印列表(用于调试)时,出现以下错误:

  NameError:名称'network'未定义

有没有简单的我做错了,还是有一个更好的方法来传递变量之间的函数而不使用全局变量? 变量不能在它们被定义的函数范围之外访问。



只需执行以下操作:

  network = splitNet()
打印网络


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

这篇关于函数的Python返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆