【问题标题】:Problems extending python array declared outside of scope扩展在范围之外声明的 python 数组的问题
【发布时间】: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


【解决方案1】:

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

希望对你有帮助。

【讨论】:

    【解决方案2】:

    这是 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2018-01-03
      • 1970-01-01
      相关资源
      最近更新 更多