2015-11-23 149 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'以该值开头。你仍然需要在列表理解中做到这一点。 –