Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 698
slackline Avatar asked Sep 27 '18 12:09

slackline


People also ask

Can you put an if statement in a list comprehension?

You can add an if statement at the end of a list comprehension to return only items which satisfy a certain condition. For example, the code below returns only the numbers in the list that are greater than two.

What is nested Listt?

A list that occurs as an element of another list (which may ofcourse itself be an element of another list etc) is known as nested list.

Can Elif be used in list comprehension?

Can we use "Elif" in a List Comprehension? No we can't use it, but there is a way to solve this challenge. Here you can see the classic solution of "FizzBuzz" problem using "If-Elif-Else" combination. To solve this challenge we can construct our List Comprehension as below.


1 Answers

you can rewrite this as follows:

new_list = [y for x in nested_list for d, y in enumerate(x) if d == 1]

loops are in the "natural" order, and the condition is in the end. Include y only if d==1

one possible result (because dicts aren't ordered):

[{'c': 3, 'd': 4}, {'c': 7, 'd': 8}]

Note that in your case, it's simpler and more efficient (O(n) vs O(n**2)) to write:

new_list = [x[1] for x in nested_list]

the only difference is that if x is too short the latter code will break so maybe test length:

new_list = [x[1] for x in nested_list if len(x)>1]
like image 192
Jean-François Fabre Avatar answered Sep 24 '22 17:09

Jean-François Fabre