2011-08-01 6 views
0

중첩 된 방식으로 호출하는 두 개의 def 함수가 있고 두 번째를 루프에서 호출하려고합니다. 현재 목록의 각 구성원을 적용하는 대신 수동으로 내 목록에 전화하는 방법에 대한 구문을 알아낼 수 있습니다. ...Python : 중첩 된 함수 호출에 목록 적용

#A list of the files I want to read 
afiles = [['awc_mm09c.txt','integer'], ['canopy01c.txt','real'], 
       ['canopy10c.txt','real'], ['canopy33c.txt','real'], 
       ['ccapnyp6c.txt','text'], ['gclass09c.txt','text'], 
       ['nyelev09c.txt','real']] 

def readfile(fn): 
    conn = open(ascPath + '\\' + fn, 'r') 
    # code to read data from the file 
def rows(*columns): 
    # code that merges data from the other files into columns 
    for ID, cols in enumerate(itertools.izip(*columns)): 
     yield [ID] + list(cols) 
# build the SQL 
strQuery = "insert into foo...;" 
# run some apsw (SQLite) code 
c.execute("begin") 
# this works. Is there any way to avoid manually listing each item in the list? 
c.executemany(strQuery, rows(readfile(afiles[0][0]), 
       readfile(afiles[1][0]), 
       readfile(afiles[2][0]), 
       readfile(afiles[3][0]), 
       readfile(afiles[4][0]), 
       readfile(afiles[5][0]), 
       readfile(afiles[6][0]))) 
c.execute("commit") 

#I've tried something like the following, but to no avail: 

c.executemany(strQuery, rows(
    for f in range(len(afiles_dt)): 
     readfile(afiles_dt[f][0]))) 

감사합니다. Tim

답변

0

이 시도하는 방법

rows(*(readfile(x[0]) for x in afiles)) 
+0

멋진! 감사. – Tim

0

'for'앞에 'readfile (afiles [i] [0])'을 옮기면됩니다. 목록 이해가 파이썬에서 작동하는 방식이기 때문입니다.

c.executemany(strQuery, rows(*[readfile(afiles[i][0]) for i in xrange(len(afiles_dt))])) 

OR :

c.executemany(strQuery, rows(*[readfile(fInfo[0]) for fInfo in afiles_dt)])) 
+0

감사합니다. Constaninius에서와 같은 대답. 빠른 도움에 정말 감사드립니다! 나는 아직도 목록 이해력을 배우고있다. – Tim

1

에 대한 rows(*map(lambda (n,t):readfile(n), afiles))

+0

내 첫 번째 시도가 내게이 오류가 발생했습니다 : "rows() 인수는 * 생성자가 아닌 시퀀스 여야합니다" 계속 작업 할 것입니다 ... – Tim

+0

@Tim : 위의 코드는 적어도 Python에서 작동해야합니다 2.5 이상. 어쩌면 이전 버전의 파이썬에서도 작동하지 않을 수도 있습니다.이 경우 괄호로'*'다음에 괄호 쌍을 바꿀 수 있습니다. –

0

에 의해 rows()에 대한 호출을 바꾸기 :

당신은 당신의 코드를 다음과 같은 방법을 업데이트 할 수 있습니다
c.executemany(strQuery, rows(
    *[readfile(afiles_dt[f][0]) for f in range(len(afiles_dt))] 
))