【问题标题】:how to append item to a global list from within a procedure如何从过程中将项目附加到全局列表
【发布时间】:2013-03-28 07:41:42
【问题描述】:

执行此操作时出现语法错误:

p = []
def proc(n):
    for i in range(0,n):
        C = i
        global p.append(C)

【问题讨论】:

  • 我认为如果你在实际问题中包含标题的内容,这个问题会得到改善。
  • 列出您遇到的具体错误。

标签: python global-variables append


【解决方案1】:

只需将其更改为以下内容:

def proc(n):
    for i in range(0,n):
        C = i
        p.append(C)

global 语句只能在函数的最顶部使用,并且只有在分配给全局变量时才需要。如果您只是修改一个可变对象,则不需要使用它。

以下是正确用法的示例:

n = 0
def set_n(i):
    global n
    n = i

如果没有上述函数中的 global 语句,这只会在函数中创建一个局部变量,而不是修改全局变量的值。

【讨论】:

  • "只能在函数的最顶层使用"——实际上并不是 100% 正确(至少在我的快速 Cpython 测试中不是)。 def set_n(): b = 1; global n; n = i + b 在您的第二个示例中有效。我认为只是 n 必须在 因为其他原因被解析之前声明为全局,但这是一个非常小的挑剔。
  • 是的,global 只需要在其所指对象被使用之前出现(如果没有,只会获得警告)。但是无论如何都要 +1 来提及修改可变与分配的区别。
【解决方案2】:

问题是您尝试直接打印列表而不是在打印之前转换为字符串,并且由于数组是学生类的成员,您需要使用“自我”来引用它。

以下代码有效:

class Student:
    array = []
    def addstudent(self,studentName):
        print("New Student is added "+studentName)
        self.array.append(studentName)
        print(str(self.array))
    def removeStudent(self,studentName):
        print("Before Removing the Students from the  list are "+ str(self.array))
        self.array.remove(studentName)
        print("After Removing the students from the list are "+ str(self.array))
if __name__ == '__main__':
   studata = Student()
   studata.addstudent("Yogeeswar")
   studata.addstudent("Linga Amara")
   studata.addstudent("Mahanti")
   studata.removeStudent("Yogeeswar")

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 2021-07-11
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多