jeudi 27 septembre 2018

Nested list comprehension with if statement

I'm trying to get my head around nested list comprehension and have read the excellent explanation here.

The problem I'm having translating is that I've an if clause in my inner loop and I can't see how to apply this to the func() step as I'm loosing the counter I get from enumerate() when I go from nested loops to list comprehension.

nested_list = [[{'a': 1, 'b': 2}, {'c': 3, 'd': 4}], [{'a': 5, 'b': 6}, {'c': 7, 'd': 8}]]
new_list = []
for c, x in enumerate(nested_list):
    for d, y in enumerate(x):
        if d == 1:
            new_list.append(y)
print(new_list)
[{'c': 3, 'd': 4}, {'c': 7, 'd': 8}]

Nested list comprehension might look something like

new_list = [if ??? y
               for x in nested_list
                   for y in x]

...but I can't see/think how to get the clause as I have no counter under the nested list comprehension.

Is there a way of achieving this or should I stick to the nested loops approach?

Aucun commentaire:

Enregistrer un commentaire