Tripple list comprehension

Question:

I have that code:

tt = []

for i in cp:
    for ii in i:
        for iii in all_numbers:
            if ii == iii[0]:
                tt.append([i, iii[1]])

How can I make the same list using comprehension?

Asked By: Breathe of fate

||

Answers:

You basically keep the for clauses in the same order.

tt = [[i,iii[1] for i in cp for ii in i for iii in all_numbers if ii == iii[0]]
Answered By: Tim Roberts

Tim Roberts has given you the direct translation of your nested loops into a list comprehension. I wanted to supplement that answer by proposing that your original code could be improved by changing the innermost loop into a dictionary lookup:

num_dict = dict(all_nums)   # map from iii[0] to iii[1] values
tt = []
for i in cp:
    for ii in i:
        if ii in num_dict:
            tt.append([i, num_dict[ii]])

# or tt = [[i, num_dict[ii]] for i in cp for ii in i if ii in num_dict]

This makes some assumptions about your data, such as that all_nums items have exactly two values (where your original code could allow for more). The version of the code above also assumes that there are no duplicate keys (e.g. that each inner loop of your original code would only find at most one match per iii value). If that’s not true, you’d need a slightly more sophisticated conversion of the data into a dictionary and then slightly different code (with a new inner loop) to handle the values:

num_dict = {}  # now we map to a list of values, without assuming uniqueness
for key, *values in all_nums:
    num_dict.setdefault(key, []).append(values)

tt = []
for i in cp:
    for ii in i:
        for iii, *rest in num_dict.get(ii, []):
            tt.append([i, iii])

# or tt = [[i, iii] for i in cp for ii in i for iii, *rest in num_dict.get(ii, [])]
Answered By: Blckknght
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.