Skip to content
Advertisement

Sorting and Grouping Nested Lists in Python

I have the following data structure (a list of lists)

JavaScript

I would like to be able to

  1. Use a function to reorder the list so that I can group by each item in the list. For example I’d like to be able to group by the second column (so that all the 21’s are together)

  2. Use a function to only display certain values from each inner list. For example i’d like to reduce this list to only contain the 4th field value of ‘2somename’

so the list would look like this

JavaScript

Advertisement

Answer

For the first question, the first thing you should do is sort the list by the second field using itemgetter from the operator module:

JavaScript

Then you can use itertools’ groupby function:

JavaScript

Now y is an iterator containing tuples of (element, item iterator). It’s more confusing to explain these tuples than it is to show code:

JavaScript

Which prints:

JavaScript

For the second part, you should use list comprehensions as mentioned already here:

JavaScript

Which prints:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement