Return 'CBA'.index(ade) / float(self.age) The same technique works for objects with named attributes. > sorted(student_tuples, key=lambda student: student) # sort by age This technique is fast because the key function is called exactly once for each input record.Ī common pattern is to sort complex objects using some of the object's indices as a key. The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. > sorted("This is a test string from Andrew".split(), key=str.lower) Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.įor example, here's a case-insensitive string comparison: In contrast, the sorted() function accepts any iterable. Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient.Īnother difference is that the list.sort() method is only defined for lists. It modifies the list in-place (and returns None to avoid confusion). You can also use the list.sort() method of a list. #Python sorty manualsThere are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here.Ī simple ascending sort is very easy - just call the sorted() function. Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable. The Old Way Using Decorate-Sort-Undecorate.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |