Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping on an attribute using itertools.groupby

Tags:

python

I have a list of instances of the class 'Chromosome'.

The list is sorted on the Chromosome attribute 'equation'

I now want to remove instances where the attribute 'equation' is the same, leaving only one.

I don't know how to pass the key, ie the ?, so that it groups on 'equation'.

b = [a for a,b in groupby(list, ?)]
like image 818
Peter Stewart Avatar asked Mar 13 '26 12:03

Peter Stewart


1 Answers

import operator

[a for a, b in groupby(thelist, operator.attrgetter('equation')]

Btw, don't use builtin type names (such as list, file, etc) for your own identifiers, it's a confusing and best-avoided practice that will eventually byte you with peculiar bugs unless you wean yourself off it (i.e one day you'll be maintaining your code, and find yourself using list(sometuple) to make a list out of some tuple, or the like... and get weird errors if you've used list to mean something different than list in this scope!-).

like image 133
Alex Martelli Avatar answered Mar 15 '26 02:03

Alex Martelli