Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to use a list comprehension here?

I have data of the following form:

foos = [{'bar': [{'baz': 1}, {'baz': 2}]}, {'bar': [{'baz': 3}, {'baz': 4}]}, {'bar': [{'baz': 5}, {'baz': 6}]}]

I want a list comprehension that will yield:

[1, 2, 3, 4, 5, 6]

I'm not quite sure how to go about doing this. This sorta works:

>>> [[bar['baz'] for bar in foo['bar']] for foo in foos]
[[1, 2], [3, 4], [5, 6]]

but I want the results to be a flattened list.

like image 330
Nick Heiner Avatar asked Dec 09 '22 11:12

Nick Heiner


2 Answers

Instead of nesting list comprehensions, you can do it with two for .. in clauses in one list comprehension:

In [19]: [item['baz'] for foo in foos for item in foo['bar']]
Out[19]: [1, 2, 3, 4, 5, 6]

Note that

[... for foo in foos for item in foo['bar']]

translates roughly into

for foo in foos:
    for item in foo['bar']:
        ...
like image 95
unutbu Avatar answered Dec 28 '22 22:12

unutbu


this will do

 [y['baz'] for x in foos for y in x['bar']]

If you think it's not really natural I agree.

Probably explicit code would be better unless there are other reasons to do that.

like image 23
6502 Avatar answered Dec 28 '22 22:12

6502