2013-04-09 3 views
0

필자가 작성한 프로그램 전체에서 목록을 사용하고 싶습니다. 기본적으로, 그것은 다른 사람들에 관한 정보를 가진 튜플들로 가득 찬리스트이고, 각 사람의 정보 (이름, 전화 번호, 주소 등)는 튜플 안에 저장됩니다. 나는 초기 함수를 통해이 목록을 정의하지만, 다른 사람들과 마찬가지로이 함수를 내 상호 작용 함수에 사용해야합니다.파이썬에서 다른 기능의 목록 사용

제 질문은이 목록을 전역 변수로 정의하지 않고 사용할 수 있습니까?

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: ') 

기능을 수행하기 위해 입력을 구문 분석하는 명령이 있다는 것도 언급해야합니다. 이것은 목록 사용에 영향을 미칩니 까?

+0

'load_friends'에서'friends_list'를 반환하고'add_friend'에서와 같이 다른 함수에 매개 변수로 전달할 수 있습니다. – Moshe

답변

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() 
+0

도움에 감사드립니다! 대우처럼 작동 – Yeto

+1

예를 들어 변수 이름으로'list'를 사용하지 마십시오. – jamylak

+0

좋은 점은 수정 하겠습니다 –

0

는 다음을 수행 할 수 있습니다 :

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

나는 확실히 당신의 질문하지만 당신이 필요로 할 것이다 그 두 가지 방법 중 하나의 마지막 부분을 이해하지 않습니다.

0

예. 함수 사이에서 "친구 목록"을 인수로 전달하십시오. list.append() 자리에 기존 목록을 변이합니다 때문에,

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에 그 지정은 불필요 :

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

클래스가 사용하는 이런 종류의 일에 유용하고 쉽게 :

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()) 

을 당신은 목록을 끝내는 "글로벌"이죠. PersInfo 개체가 인스턴스화되는 곳은 main()입니다. 이는 원하는 것 이상일 수 있지만 장기적으로 코드를 구성하고 읽을 수있는 좋은 방법입니다.

또한 person_list을 직접 작성하여 infoList을 만들 수 있습니다.

+0

이 모든 게터와 설정자는 무엇입니까? 이것은 [남자] (http://dirtsimple.org/2004/12/python-is-not-java.html)가 말했듯이, 자바가 아닌 파이썬입니다. – DSM

+0

네, 맞습니다. @DSM. 더 나은 코드가 속성에 직접 액세스 할 것을 제안합니까? 'foo.name = 'someString'과 같습니다. – mrKelley