简体   繁体   English

Python:嵌套列表理解

[英]Python: nested list comprehension

I have a nested list issue that I cannot solve. 我有一个无法解决的嵌套列表问题。

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)

This produces an ouput: 这将产生一个输出:

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

I was wondering what the best way is to do a list comprehension is, so that the output would be: 我想知道进行列表理解的最好方法是什么,以便输出为:

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

You can do this with a nested list comprehension: 您可以使用嵌套列表理解来做到这一点:

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

You probably want to make the second_set a set of just the a[0] values: 您可能希望将second_set设置为包含a[0]值的集合:

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

simplifying things a little in your list comprehension 简化列表理解中的内容

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

Your sample outputs seem to be based on the print statement, not the actual values appended to the result list. 您的示例输出似乎基于print语句,而不是实际值附加到result列表中。 Your print statements include the id value too; 您的print语句也包含id值; if this is needed, just add it in: 如果需要,只需将其添加到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM