【发布时间】:2016-09-03 04:48:01
【问题描述】:
这是一个非常基本的问题,但我似乎无法使用在函数中添加的新项来扩展数组。我也没有努力工作,所以我认为我的数组没有被其他函数处理。
数组被声明为全局数组,否则函数似乎无法看到它。可能有更好的方法,但这在几个方面是有效的。
这是我尝试过的一组事情:
# addTo.insert(0, theItem)
# weeklytasks.append(theItem)
# print(addTo)
# def askForItem(theItem):
# addTo.push(theItem)
# print(addTo)
#
但没有运气。
def initializer():
print("hello!")
print("do you want to view the current list, or add a new item?")
设置一些数组
global weeklyTasks = ['no items'];
global monthlyTasks = ['no items']
global quarterlyTasks = ['no items'];
试图扩展
quarterlyTasks.extend('the item')
print(quarterlyTasks);
这些都不起作用
#monthlyTasks.push(0,"task1")
#monthlyTasks.append("item")
为用户的输入设置一个变量
global theItem
addTo = ""
theItem = ""
import string
print('addTo in globals, ' 'addTo' in globals())
取出一个项目并检查它的时间范围
def evaluateInput(timeframe):
global addTo;
global theItem;
if timeframe == "Weekly":
addTo = "weeklyTasks";
printDestination();
weeklyTasks.extend(theItem); # why does [].extend not work here?
if timeframe == "Monthly":
addTo = "monthlyTasks"
monthlyTasks.insert(0,theItem)
printDestination()
if timeframe == "Quarterly":
addTo = "quarterlyTasks"
quarterlyTasks.insert(0,theItem)
printDestination()
跟进时间范围的请求
def getTimeframe(text):
if "add" in text:
timeframe = input("Where does this entry go? \n Weekly, Monthly or Quarterly?: ")
evaluateInput(timeframe) # sends the timeframe to evaluateInput
# next, ask for the item
theItem = input('what is the item?')
打印确认添加的内容
def printDestination():
print("The item (" + theItem+") will be added to " + addTo)
# prints where something is going
print("the "+addTo+" list now contains:") # good, this worked
print(weeklyTasks) #good, this worked (but the method to push doesn't work)
【问题讨论】:
-
你在初始化函数中定义你的全局变量吗?这有点难说。如果是这样,请记住您需要在全局变量可用之前调用初始化函数。 (我建议在您的示例中修复缩进 - 很难判断哪个代码块中的代码。)
-
你是什么意思他们“不工作?”他们怎么不工作
-
Python 不使用分号结束一行
标签: python arrays python-3.x