python sort sorted sort and

When we get a write data from the database, the general problem for the sorted list is often encountered today summarize common method for python list to sort the list:

The first: Built sort () method

You can sort the list by direct

usage:

list.sort(func=None, key=None, reverse=False(or True))

  • For reverse type bool This parameter, when reverse = False: forward ordering; When reverse = True when: a direction sorting. The default is False.
  • After the implementation will change the original list, if you do not need the original list, this little high efficiency
  • To avoid confusion, it will return none

E.g

The second: built-in function sorted ()

This and the first difference is that:

  • sorted () does not change the original list, but will return a new list has been sorted
  • the list.sort () method is only defined list, sorted () may be used for any iterable

usage:

sorted(list)

  • The function also contains the reverse type bool parameters, when reverse = False: forward order (ascending); When reverse = True when: a reverse order (descending). Of course, the default is False.
  • It will return after the implementation of a new sorted list

E.g:

Extended Usage:

1.Key Function:

Python2.4 from the start, list.sort () and sorted () have added a 'key' parameter is used to specify the function of making comparisons on each list element to be called before.

E.g:

Case-insensitive string comparison sort:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

key should be a function that takes one argument, and returns a key for the sort. Its high efficiency, because it can accurately be called for input record key function.

For complex objects, using the object as the index key.

E.g:

>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Properties of the object using the operation:

E.g:

>>> class Student:
...     def __init__(self, name, grade, age):
...         self.name = name
...         self.grade = grade
...         self.age = age
...     def __repr__(self):
...         return repr((self.name, self.grade, self.age))
>>>
>>> student_objects = [
...     Student('john', 'A', 15),
...     Student('jane', 'B', 12),
...     Student('dave', 'B', 10),
... ]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Some time ago this happens, it is a list which each element more than one element (for example: a list of inside element is the ancestral type), we not only want to but the first key sort, would also like the first time basis of the above are sorted according to the second keyword, just used this method:

A simplified example:

We would like to sort the first list of keywords list of elements, and then sorted by the second sorting based on keywords on the first element, look at the results:

>>> list = [('d',3),('a',5),('d',1),('c',2),('d',2)]
>>> print sorted(list, key = lambda x:(x[0],x[1]))
[('a', 5), ('c', 2), ('d', 1), ('d', 2), ('d', 3)]

2.Operator Module Functions

2.Operator Module Functions

This operation modules are:

  • operator.itemgetter()   ----- 通过下标
  • operator.attrgetter()   ----- 通过参数
  • operator.methodcaller() -----python 2.5 被引入,下文详细介绍

Use these functions will be more convenient for the example above Key Function up and fast processing

First an introduction operator.itemgetter () and operator.attrgetter () and maybe has, easier to understand:

E.g:

>>> from operator import itemgetter, attrgetter
>>>
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>>
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The operating module also allows multi-level sorting, for example you can first sort "results grand" re-ordering "age age"

E.g:

>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
>>>
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

Now come back to find that the above problems encountered in the previous few days, can be solved by this operator.itemgetter:

>>> list = [('d',3),('a',5),('d',1),('c',2),('d',2)]
>>> from operator import itemgetter
>>> sorted(list, key=itemgetter(0,1))
[('a', 5), ('c', 2), ('d', 1), ('d', 2), ('d', 3)]

However, it is recommended that the method 1.key function, because in order to introduce this sort and a library, relatively more harm than good.

Here operator.methodcaller () function:

This function is the use of a fixed parameter of an object sorting, for example: str.count () function to count the number of objects contained in each string of a parameter, then the use of this function I can str.count ( ) is calculated so that a certain number of characters to determine the priority ordering:

>>> from operator import methodcaller
>>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!']
>>> sorted(messages, key=methodcaller('count', '!'))
['standby', 'hurry!', 'immediate!!', 'critical!!!']

3. Note:

Sort of stability:

Starting python2.2 version, it is to protect the stability of the sort, meaning that, when the complex sorting, the objects have the same key when the original order will remain the same:

E.g:

>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> sorted(data, key=itemgetter(0))
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
Can be seen, ( ' Blue ' ,. 1) and ( 'Blue', 2 ) in order to maintain the original or the like is not changed.

Complex Sort by:
This sort of property lets you build complex sorting operations in a series of steps. Such as the above example, sort, I would like to operate descending through the "achievements grand" and then by "age age" ascending operation, first to the "age of age" sort, and then through the "achievements grand" Sort by:
>>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
>>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

4. New questions:

Today encountered such a problem is encountered handling problems of a string, for example, was at the back f10 f2. So find a way, for reference:

Reference Address: http: //blog.csdn.net/houyj1986/article/details/22966799

 

 

Guess you like

Origin www.cnblogs.com/1a2a/p/11016366.html