Python: 嵌套列表理解

Python: nested list comprehension

我有一个无法解决的嵌套列表问题。

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

您可以使用嵌套列表理解来做到这一点:

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