python list of small operations

List or a list of string values, can sort () method to sort. For example, in an interactive environment lose
Enter the following code:
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
You can also specify reverse keyword argument is True, so that sort () to sort in reverse order. In an interactive environment
Enter the following code:
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
 
About sort () method, you should pay attention to three things. First, sort () method on the spot to sort the list. Do not
Write spam = spam.sort () such code, attempting to record the return value.
Secondly, you can not sort the list of both numbers of string values, because Python does not know how to compare
they. Enter the following code in an interactive environment, pay attention to a TypeError:
>>> spam = [1, 3, 2, 4, 'Alice', 'Bob']
>>> spam.sort()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
spam.sort()
TypeError: unorderable types: str() < int()
Third, when the sort () method to sort strings, using the "ASCII character sequence", rather than the actual word
Code sequence. This means uppercase letters before lowercase letters. Therefore, when sorting a lowercase in uppercase
After Z. For example, enter the following code in an interactive environment:
>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
>>> spam.sort()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']
If you need to be sorted ordinary dictionary order, when in the sort () method call, the key parameters
key to str.lower.
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam
[ 'A', 'A', 'z', 'Z']

Guess you like

Origin www.cnblogs.com/yangyublog/p/11431017.html