首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python 3列表

使用Python 3列表
EN

Stack Overflow用户
提问于 2015-01-25 14:07:42
回答 3查看 121关注 0票数 2

Python (3)列表有一些问题。

代码语言:javascript
复制
def initLocations():
    locName = ["The Town","The Blacksmith Hut"]
    locDesc = ["A small but beautiful town. You've lived here all your life.",     "There are many shops here, but the Blacksmith Hut is the most intricate."]

这是脚本的顶部。稍后,它将由以下名称调用:

代码语言:javascript
复制
initLocations()

然后大约4行之后:

代码语言:javascript
复制
while currentLoc<20:
    initLocations()
    print("Type 'Help' for advice on what to do next.")
    passedCommand = input("?: ")
    mainProcess(passedCommand)

更多信息在这里:http://pastebin.com/5ib6CJ4g

继续得到错误

代码语言:javascript
复制
print("Left: " + locName[currentLoc-1])
NameError: name 'locName' is not defined

任何帮助都很感激。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-01-25 14:13:46

函数中定义的变量是该函数的本地变量。它们不会泄漏到调用范围(这是一件好事)。如果您想要函数提供可用的东西,则需要返回它们。例如:

代码语言:javascript
复制
def initLocations():
    locName = […]
    locDesc = […]
    return locName, locDesc

这将使函数返回一个包含名称列表和描述列表的二元组。在调用函数时,您将需要捕获这些值并再次将它们保存到变量中。例如:

代码语言:javascript
复制
locName, locDesc = initLocations()
票数 2
EN

Stack Overflow用户

发布于 2015-01-25 14:13:12

仅仅调用一个函数并不会在外部范围内创建变量。您将不得不使他们global,但这是一个非常糟糕的方式做一些事情。您需要从函数中return它。在initLocations()中,您需要有一个语句return locName,当您调用它时,您需要使用locName = initLocations()。如果您有两个变量,则需要将它们作为元组发送。

演示

代码语言:javascript
复制
def initLocations():
    locName = ["The Town","The Blacksmith Hut"]
    locDesc = ["A small but beautiful town. You've lived here all your life.",     "There are many shops here, but the Blacksmith Hut is the most intricate."
    return (locName,locDesc)

然后

代码语言:javascript
复制
while currentLoc<20:
    locName,locDesc = initLocations()
    print("Type 'Help' for advice on what to do next.")
    passedCommand = input("?: ")
    mainProcess(passedCommand)

这被称为元组包装序列解压。

小票

正如Padraic在comment中提到的,拥有一个函数来声明这两个列表是非常无用的(除非你必须这样做)。

你可以这样做,

代码语言:javascript
复制
locName = ["The Town","The Blacksmith Hut"]
locDesc = ["A small but beautiful town. You've lived here all your life.",     "There are many shops here, but the Blacksmith Hut is the most intricate."
while currentLoc<20:        
    print("Type 'Help' for advice on what to do next.")
    passedCommand = input("?: ")
    mainProcess(passedCommand)

这是一个更好的方法

票数 1
EN

Stack Overflow用户

发布于 2015-01-25 14:15:14

initLocations内部的作用域不是全局的。除非变量声明为global或函数作为值返回,否则在该函数的作用域外部(包含范围级别)中将无法使用在该函数范围内创建的值。

第二种办法非常可取:

代码语言:javascript
复制
def initLocations():
    locName = ["The Town","The Blacksmith Hut"]
    locDesc = ["A small but beautiful town. You've lived here all your life.",     
               "There are many shops here, but the Blacksmith Hut is the most intricate."]
    return locName, locDesc

然后,在稍后调用该函数时:

代码语言:javascript
复制
locName, locDesc = initLocations()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28137283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档