Python list sort problem __python

Source: Internet
Author: User

To sort the list, Python provides two methods

---sort----
Method 1. Sorting using the List.sort function of list

List.sort (Func=none, Key=none, Reverse=false)
Method 2. Sort by sequence type function sorted (list)

>>> list = [2,5,1]  
>>> list  
[2, 5, 1]  
>>> sorted (list)  
[1, 2, 5]  
> >> list  
[2, 5, 1]  
>>> list.sort ()  
>>> list  
[1, 2, 5]  

Sorted (list) Returns an object that can be used as an expression. The original list does not change, creating a new sorted list object.

List.sort () does not return the object, changing the original list.

Example 1:
>>>l = [2,3,1,4]
>>>l.sort ()
>>>l
>>>[1,2,3,4]
Example 2:
>>>l = [2,3,1,4]
>>>l.sort (Reverse=true)
>>>l
>>>[4,3,2,1]


Sort the Second keyword:

Example 3:

>>>l = [(' B ', 6), (' A ', 1), (' C ', 3), (' d ', 4)]
>>>l.sort (Key=lambda x:x[1])
>>>l
>>>[(' A ', 1), (' C ', 3), (' d ', 4), (' B ', 6)]

>>>l = [(' B ', 2), (' A ', 1), (' C ', 3), (' d ', 4)]

Example 4:
>>>import operator
>>>l.sort (Key=operator.itemgetter (1))
>>>l
>>>[(' A ', 1), (' B ', 2), (' C ', 3), (' d ', 4)]

(operator module for detailed usage please take part in the previous blog.) )


What if we want to order the second keyword and then sort it with the first keyword? There are two ways
Example 5:
>>> L = [(' d ', 2], (' A ', 4), (' B ', 3), (' C ', 2)]
>>> L.sort (Key=lambda x: (x[1],x[0))
>>> L
>>>[(' C ', 2), (' d ', 2), (' B ', 3), (' A ', 4)]
Example 6:
>>> L = [(' d ', 2], (' A ', 4), (' B ', 3), (' C ', 2)]
>>> L.sort (Key=operator.itemgetter (1,0))
>>> L
>>>[(' C ', 2), (' d ', 2), (' B ', 3), (' A ', 4)]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.