开发者

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 th开发者_开发百科at 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜