0 votes
1 view
in Python by (580 points)

I've got a list of Python objects which I would like to sort by an attribute of the objects themselves. The list is as follows:

>>> nt

[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>,

 <Tag: aes>, <Tag: ajax> ...]

 

Each object has a count:

 

>>> nt[1].count

1L

 

I want the list be sorted by number of counts descending.Can anyone help?

1 Answer

0 votes
by (10.9k points)

You can use the sort() method to sort a list in place.

nt.sort(key=lambda x: x.count, reverse=True)

 

Alternatively, you can use the sorted() built-in function to return a new sorted list.

sorted_list = sorted(nt, key=lambda x: x.count, reverse=True) 

To know more about sorting in python take a look here: https://wiki.python.org/moin/HowTo/Sorting#Ascending_and_Descending

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...