【问题标题】:Use a list in different functions in python在python的不同函数中使用列表
【发布时间】:2013-04-09 13:59:26
【问题描述】:

我想在我正在编写的程序中使用一个列表。基本上,它是一个包含不同人信息的元组列表,每个人的信息(姓名、电话、地址等)都存储在一个元组中。我通过一个初始函数定义了这个列表,但我需要在我的交互函数以及其他函数中使用它。

我的问题是,我是否可以使用此列表而不将其定义为全局变量?

def load_friends(filename):
    """imports filename as a list of tuples using the import command"""
    import csv
    with open(filename, 'Ur')as filename:
        friends_list = list(tuple(x) for x in csv.reader(filename, delimiter=','))

def add_friend(friend_info, friends_list):
    """appends the friend_info tupple to the list friends_list"""
    new_list = friends_list.append(friends_info)

def interact():
    """interaction function: accepts user input commands"""
    while True:
        command = raw_input('Command: ')  

我还应该提到,有一个命令可以解析使用输入以执行功能。这会影响列表的使用吗?

【问题讨论】:

  • 您可以从load_friends 返回friends_list 并将其作为参数传递给其他函数,就像在add_friend 中那样。

标签: python list function global-variables


【解决方案1】:

您可以在第一个调用它的函数中声明 list 并从那里返回它,然后后面的函数应该接收这个 list 作为参数。

def func1():
    my_list=[]
    """Do stuff
    """
    return list

def func2(my_list):
    """Do stuff with my_list
    """
    return

def func3(my_list):
    """Do stuff with my_list
    """
    return

def main():
    """First we retrieve the list from func1, 
    func2/3 get it passed to them as an argument
    """
    foo=func1
    func2(foo)
    func3(foo)

if __name__ == "__main__":
    main()

【讨论】:

  • 不要使用list作为变量名,即使是示例
【解决方案2】:

您可以执行以下操作:

# you can define the list here, it's global but doesn't require the keyword    
my_list_globally = []

def func1(the_list):
    pass

def func2(the_list):
    pass

def func3(the_list):
    pass

# you can use a hub function to pass the list into things that need it
def main():
    my_list = []
    func1(my_list)
    func2(my_list)
    func3(my_list)

if __name__ == "__main__":
    main()

我不太明白你问题的最后一部分,但是这两种方法中的一种就是你需要的。

【讨论】:

    【解决方案3】:

    是的。在函数之间来回传递“朋友列表”作为参数。

    load_friends() 会变成

    def load_friends(filename):
        import csv
    
        with open(filename, 'Ur') as f:
            return map(tuple, csv.reader(f, delimiter=","))
    

    add_friend() 很接近,但分配给new_list 是不必要的,因为list.append() 会改变现有列表:

    def add_friend(friend_info, friend_list):
        friend_list.append(friend_info)
    

    足够了。

    interact() 也会有一个 friends_list 参数。

    def interact(friends_list):
        #interaction stuff here...
    

    你可以这样称呼它:

    interact(load_friends("myfile.csv"))
    

    【讨论】:

      【解决方案4】:

      类对这类事情很有用,而且易于使用:

      class PersInfo:
      
          def setName(self, name):
              self._name = name
      
          def getName(self):
              return self._name
      
          def setNumber(self, number):
              self._phNumber = number
      
          def getNumber(self):
              return self._phNumber
      
          def setAddr(self, address):
              self._address = address
      
          def getAddr(self)
              return self._address
      
      def main():
          # Read in data from your CSV Here
      
          infoList = ([])
          for person in person_list: # Assuming person is a tuple here
              foo = PersInfo()
              foo.setName(person[index1])
              foo.setNumber(person[index2])
              foo.setAddr(person[index3])
              infoList.append(foo)
      
          # To access the info...
          for person in infoList:
              print(person.getName())
              print(person.getNumber())
              print(person.getAddr())
      

      你最终会得到一个“全球”的列表。它位于main() 函数中,其中PersInfo 对象正在被实例化。这可能超出了您的预期,但从长远来看,这是组织代码并保持可读性的好方法。

      另外,您可以在您创建 person_list 的地方直接构建我创建的 infoList

      【讨论】:

      • 所有这些 getter 和 setter 是怎么回事?正如the man 所说,这是 Python,而不是 Java。
      • 是的,你是对的@DSM。您是否建议更好的代码直接访问属性?喜欢foo.name = 'someString'
      猜你喜欢
      • 2012-10-14
      • 2017-07-22
      • 2013-10-31
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多