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.
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']:
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With