扩展在范围

时间:2016-09-03 04:48:01

标签: python arrays python-3.x

这是一个非常基本的问题,但我似乎无法使用函数中添加的新项扩展数组。我也没有努力工作,所以我认为我的阵列没有被其他功能解决。

数组被声明为全局,因为否则函数似乎无法看到它。可能有更好的方法,但这有一些方法。

这是我试过的一系列事情:

        # 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")

为用户输入设置var

        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)

2 个答案:

答案 0 :(得分:3)

所有提到的功能的工作示例。 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']

希望它有所帮助。

答案 1 :(得分:1)

这是python 3.2中的工作解决方案,用于在项目中添加项目列表:

weeklyTasks = ['No work Sunday']
def AddWeeklyTask():
    weeklyTasks.extend(['Work On'])
    weeklyTasks.append('Do not work on weekends')
    weeklyTasks.insert(2,'Friday')

print(weeklyTasks)
AddWeeklyTask()
print(weeklyTasks)

输出:

['No work Sunday']
['No work Sunday', 'Work On', 'Friday', 'Do not work on weekends']

无需将list声明为global

相关问题