简体   繁体   中英

Grouping on an attribute using itertools.groupby

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, ?)]
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 (ie 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!-).

这是怎么做的:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM