2011-08-01 13 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]))) 

在此先感謝。蒂姆

回答

0

試試這個:

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

太棒了!謝謝。 – Tim

0

你只需要動「的ReadFile(afiles [I] [0])」之前「的」 - 因爲這是列表理解Python中的工作方式。您可以更新您的代碼如下方式:

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(*(readfile(x[0]) for x in afiles)) 
+0

我第一次嘗試在這給了我這個錯誤: 「行()*後的參數必須是一個序列,而不是發電機」 我會在它繼續工作... – Tim

+0

@Tim:以上的工作應該至少在Python 2.5或以上。也許它並不適用於更老版本的Python,在這種情況下,你可以在'*'用方括號後更換一對括號的工作。 –

0

更換呼叫rows()如何rows(*map(lambda (n,t):readfile(n), afiles))