2015-11-23 148 views
0

我有一個我無法解決的嵌套列表問題。Python:嵌套列表理解

first_list = cursor.execute('SELECT id, number, code FROM test').fetchall() 

second_list = cursor.execute('SELECT key FROM test2').fetchall() 

second_set = set(second_list) 

results = [] 

for id, number, code in first_list: 
    name = [code] 
    for a in second_set: 
     if code.startswith(a[0]): 
      if a[0] not in name: 
       name.append(a[0]) 
    results.append(tuple(name)) 


    print (id, code, name) 

這將產生一個輸出繼電器:

('1', '98', ['1', '2']) 
('2', '12', ['1', '2', '3']) 

我在想,最好的辦法就是做一個列表的理解是什麼,從而使輸出將是:

('1', '98', '1') 
('1', '98', '2') 
('2', '12', '1') 
('2', '12', '2') 
('2', '12', '3') 
+0

從不在輸出元組中包含'id',只在'print'語句中。這是由設計? –

+0

注意,如果您從數據庫中選擇唯一的直線,您將獲得更好的性能。您將獲取更少的數據,同時也跳過了Python中唯一性的代價。就像做'cursor.execute('SELECT DISTINCT(key)FROM test2')一樣簡單。「。fetchall()' – zsquare

+0

@zsquare謝謝。我想把它改爲一個集合是有點沒有意義的,當我可以在sql – user47467

回答

4

你可以做一個嵌套的列表理解:

results = [(code, a[0]) 
      for id, number, code in first_list 
      for a in second_set 
      if code.startswith(a[0])] 

你可能想使second_set一套只是a[0]值:

second_set = {a[0] for a in second_list} 

簡化的東西一點點在你的列表理解

results = [(code, a) 
      for id, number, code in first_list 
      for a in second_set if code.startswith(a)] 

你的樣品產出似乎是基於對print聲明,而不是附加到result列表的實際值。您的print聲明也包含id值;如果需要,請將其添加到:

results = [(id, code, a) 
      for id, number, code in first_list 
      for a in second_set if code.startswith(a)] 
+0

中做到這一點我不知道我是否理解正確。爲什麼我們需要在這裏開始? –

+0

另外,這似乎產生了我已經有的相同的輸出? – user47467

+0

@AkshayHazari:原始代碼僅包含'second_set'中的值,其中'code'以該值開頭。你仍然需要在列表理解中做到這一點。 –