Skip to main content
change variable name to make intentions clearer
Source Link
tzot
  • 96.5k
  • 30
  • 151
  • 210

A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

try: import operator
except ImportError: cmpfun=keyfun= lambda x: x.count # use a lambda if no operator module
else: cmpfun=keyfun= operator.attrgetter("count") # use operator since it's faster than lambda

ut.sort(key=cmpfunkey=keyfun, reverse=True) # sort in-place

A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

try: import operator
except ImportError: cmpfun= lambda x: x.count # use a lambda if no operator module
else: cmpfun= operator.attrgetter("count") # use operator since it's faster than lambda

ut.sort(key=cmpfun, reverse=True) # sort in-place

A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

try: import operator
except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module
else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda

ut.sort(key=keyfun, reverse=True) # sort in-place
Source Link
tzot
  • 96.5k
  • 30
  • 151
  • 210

A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

try: import operator
except ImportError: cmpfun= lambda x: x.count # use a lambda if no operator module
else: cmpfun= operator.attrgetter("count") # use operator since it's faster than lambda

ut.sort(key=cmpfun, reverse=True) # sort in-place