[英]Use a list in different functions in python
我想在正在编写的程序中使用列表。 基本上,它是一个充满元组的列表,其中包含有关不同人的信息,每个人的信息(姓名,电话,地址等)都存储在元组中。 我通过初始函数定义此列表,但是我需要在交互函数以及其他函数中使用此列表。
我的问题是,是否可以在不将其定义为全局变量的情况下使用此列表?
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: ')
我还应该提到,有一个命令可以解析使用输入以执行功能。 这会影响列表的使用吗?
您可以在第一个调用它的函数中声明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()
您可以执行以下操作:
# 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()
我不太了解您的问题的最后一部分,但是这两种方式之一就是您所需要的。
是。 在函数之间来回传递“朋友列表”作为参数。
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"))
类对于这种事情很有用,并且易于使用:
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
对象。 这可能比您想要的要多,但是从长远来看,这是组织代码并使代码保持可读性的好方法。
此外,您可以建立infoList
我直接对要在其中创建person_list
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.