Grouping an attribute with itertools.groupby

I have a list of instances of the Chromosome class.

The list is sorted by the Chromosome 'equation' attribute

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

I don't know how to pass the key, ie?, So it is grouped by "equation".

b = [a for a,b in groupby(list, ?)]

      

+2


source to share


2 answers


import operator

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

      



Btw, do not use the built-in type names (eg list

, file

etc.) for your own identity, it is the most intricate and avoids practices that will ultimately lead you to a certain error if you do not separate yourselves (ie one day you will maintain your code and end up with help list(sometuple)

to make a list from some tuple or the like ... and get weird errors if you used list

something other than list

in this area to denote !-).

+6


source


Here's how to do it:



b = [a for a,b in groupby(list, key=lambda a: a.equation)]

      

+3


source







All Articles