user47467
user47467

Reputation: 1093

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

Upvotes: 0

Views: 198

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124788

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] 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. Your print statements include the id value too; 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)]

Upvotes: 4

Related Questions