sorted() function is stable, that is, sorting does not change the relative position of the original data.
The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal - this is helpful for sorting in multiple passes.
Use the Operator module function
Import related module:
>>> from operator import itemgetter, attrgetter, methodcaller
For example, use the attrgetter() function, you can sort according to the specified properties. For example:
If you try to add a different type of element in the Array object, it will throw an exception:
>>> a.append(3.14)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: integer argument expected, got float
If you try to add an element that exceeds the length of the array's object, it will throw an exception:
>>> a = array('B', [1, 2, 3, 4, 5])
>>> a.append(300)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: unsigned byte integer is greater than maximum
Array objects can be converted to List:
>>> a.tolist()
[1, 2, 3, 4, 5]
Array bisection
If a list is already in order, use the Bisect module and use the left / right biction method, we can quickly find the location of an element in the list.
bisec.bisect () and bisect.bisect_right () returns the index on the right side of the elements, and bisect.bisect_left () returns the index of the left side of the elements.
Use bisect.insort () to insert an element to a list quickly and keep the list sorted, for example:
bisect can be used to do array lookup based on breakpoints, for example, we want to know the results of the grade, we can first find the score, then look for grades according to index: