Python list sort

Source: Internet
Author: User
Tags python 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]
Example 3: Sort the second keyword
>>>l = [(' B ', 6), (' A ', 1), (' C ', 3), (' d ', 4)]
>>>l.sort (Lambda x,y:cmp (x[1],y[1]))
>>>l
>>>[(' A ', 1), (' C ', 3), (' d ', 4), (' B ', 6)]
Example 4: Sort the second keyword
>>>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)]
Example 5: Sort the second keyword
>>>l = [(' B ', 2), (' A ', 1), (' C ', 3), (' d ', 4)]
>>>import operator
>>>l.sort (Key=operator.itemgetter (1))
>>>l
>>>[(' A ', 1), (' B ', 2), (' C ', 3), (' d ', 4)]
Example 6: (DSU method: Decorate-sort-undercorate)
>>>l = [(' B ', 2), (' A ', 1), (' C ', 3), (' d ', 4)]
>>>a = [(x[1],i,x) for i,x in Enumerate (L)] #i can confirm the stable sort
>>>a.sort ()
>>>l = [s[2] for s in A]
>>>l
>>>[(' A ', 1), (' B ', 2), (' C ', 3), (' d ', 4)]
The above gives the method of sorting the list in 6, where instance 3.4.5.6 can play an item in the list item
Sort the comparison keywords.
Efficiency comparison:
CMP < DSU < key
Comparing with the experiment, Method 3 is slower than method 6, method 6 is slower than Method 4, Method 4 and Method 5 are basically equivalent
Multi-keyword comparison sort:
Example 7:
>>>l = [(' d ', 2), (' A ', 4), (' B ', 3), (' C ', 2)]
>>> L.sort (Key=lambda x:x[1])
>>> L
>>>[(' d ', 2), (' C ', 2), (' B ', 3), (' A ', 4)]
As we can see, the sort of L is now sorted by the second keyword only,

What if we want to order the second keyword and then sort it with the first keyword? There are two ways
Example 8:
>>> 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 9:
>>> 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)]




For simple list ordering, call the built-in function directly, but for the Dict list sort is not so straightforward, but there is a very concise approach, such as:

>>> LS1 = [{' A ': 1, ' B ': ' 1}, {' A ': '-' + ', ' B ': 22},{' a ': ', ' B ': 32},{' a ': 6, ' B ': 42}]
>>> Ls1.sort (Key=lambda obj:obj.get (' a '))
>>> LS1
[{' A ':-1, ' B ': +}, {' A ': 1, ' B ': +}, {' A ': 6, ' B ': $ ', {' a ': +, ' B ': 32}]
>>>

Dict and list sorting in Python
1. List sort
List sorting is a python built-in feature that itself contains the Sort method
Such as:
>>> s=[2,1,3,0]
>>> S.sort ()
[0, 1, 2, 3]
2, Dict sort
Sort the dictionary, because each item includes a key-value pair, so select a comparable key or value to sort

Sorted (iterable[, cmp[, key[, reverse]]
CMP and key typically use lambda
Such as:
>>> d={"OK": 1, "No": 2}
Sort the dictionary keys and return them in the form of a tuple list
>>> Sorted (D.items, Key=lambda d:d[0])
[(' No ', 2), (' OK ', 1)]
Sorts dictionaries by value and returns them as a tuple list
>>> Sorted (D.items, Key=lambda d:d[1])
[(' OK ', 1), (' No ', 2)]
3, tuple list sorting
Such as
>>> li=[(2, ' a '), (4, ' B '), (1, ' d ')]
>>> Li.sort ()
[(1, ' d '), (2, ' a '), (4, ' B ')]
If a dictionary is sorted by the first element of an item, you can convert the Narimoto group list to
>>> d={"OK": 1, "No": 2}
>>> tt=[tuple (item) for item in D.items ()]
>>> Tt.sort ()
[(' No ', 2), (' OK ', 1)]
4 other people's realization, retention memo
Here is an example of a structure


>>> class Test:
def __init__ (self,a,b):
SELF.A = A
SELF.B = b
>>> test1 = Test (5,25)
>>> test2 = Test (10,15)
>>> tests = [Test1,test2]
>>> sorted (tests,cmp = Lambda x,y:cmp (x.a, y.a))

>>> result = sorted (Tests,key = lambda d:d.a)
5.

# (IMHO) The simplest approach:
def sortedDictValues1 (adict):
Items = Adict.items ()
Items.Sort ()
return [value for key, value in items]

# An alternative implementation, which
# happens to run a bit faster for large
# Dictionaries on my machine:
def sortedDictValues2 (adict):
Keys = Adict.keys ()

Keys.sort ()

return [Dict[key] for key in keys]

# A further slight speed-up on my box
# is to map a bound-method:
def sortedDictValues3 (adict):
Keys = Adict.keys ()
Keys.sort ()
return map (Adict.get, keys)
  • Related Article

    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.