这是一个非常基本的问题,但我似乎不能用在函数中添加的新项来扩展数组。我也没有让push工作,所以我认为我的数组没有被其他函数处理。你知道吗
数组被声明为全局数组,因为否则函数似乎无法看到它。可能有更好的方法,但这在几个方面是有效的。你知道吗
这是我尝试过的一套方法:
# 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)
所有提到的函数的工作示例。
global
不是必需的,因为函数中没有重新分配tasklist
,只调用它的方法。你知道吗希望有帮助。你知道吗
下面是python 3.2中向函数中的列表添加项的工作解决方案:
输出:
无需将
list
声明为global
相关问题 更多 >
编程相关推荐