This question already has an answer here:
Is the a short syntax for joining a list of lists into a single list( or iterator) in python?
For example I have a list as follows and I want to iterate over a,b and c.
x = [["a","b"], ["c"]]
The best I can come up with is as follows.
result = []
[ result.extend(el) for el in x]
for el in result:
print el
I had a similar problem when I had to create a dictionary that contained the elements of an array and their count. The answer is relevant because, I flatten a list of lists, get the elements I need and then do a group and count. I used Python's map function to produce a tuple of element and it's count and groupby over the array. Note that the groupby takes the array element itself as the keyfunc. As a relatively new Python coder, I find it to me more easier to comprehend, while being Pythonic as well.
Before I discuss the code, here is a sample of data I had to flatten first:
It is a query result from Mongo. The code below flattens a collection of such lists.
First, I would extract all the "entities" collection, and then for each entities collection, iterate over the dictionary and extract the name attribute.
This works recursively for infinitely nested elements:
Result:
shortest!