这是一个非常基本的问题,但我似乎无法使用在函数中添加的新项来扩展数组。我也没有被迫工作,所以我认为我的数组只是没有被其他函数处理。
数组被声明为全局数组,否则函数似乎看不到它。可能有更好的方法,但这在某些方面是可行的。
这是我试过的一组东西:
# 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
不会在函数中重新分配,只会调用它的方法。
tasklist = ['one']
def testfunc():
# no global required
tasklist.append('two')
tasklist.extend(['three', 'four'])
tasklist.insert(0, 'zero')
testfunc()
print(tasklist)
# ['zero', 'one', 'two', 'three', 'four']
希望对您有所帮助。
关于python - 扩展在范围外声明的 python 数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303338/