Python: How to use list comprehension here?

I have data of the following type:

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

I need a list comprehension that will give:

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

I'm not quite sure how to do this. This sorting 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.

+4
source share
3 answers

it will do

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

If you think this is really unnatural, I agree.

Explicit code would probably be better if there were no other reason for this.

+4
source

Instead of understanding the nesting list, you can do this with two for .. in sentences in one list view:

 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']: ... 
+10
source
 foos = [{'bar': [{'baz': 1}, {'baz': 2}]}, {'bar': [{'baz': 3}, {'baz': 4}]}, {'bar': [{'baz': 5}, {'baz': 6}]}] for x in foos: for y in x: for i in range(len(x[y])): for z in x[y][i]: print x[y][i][z] 
0
source

Source: https://habr.com/ru/post/1338149/


All Articles