Python-Ref > Data structures > List > Sorting list items
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Sorting list items

Luckily for the users, Python contains builtin support for sorting of list items, thus sparing the programmers effort that could be used elsewhere.
The task of sorting a list is easily accomplished using the lists method sort. One of the optional arguments (reverse) for this method enable reversal of the sorting.
Expand/Shrink
Zdroj: (list5-1.py)
  1   xs = [1, 2, 100, 20.5, 72, -6, 8, 26.3, 42, 77, 2]
  2   print xs
  3   xs.sort()
  4   print xs
  5   print
  6   
  7   strings = ["John", "Wendy", "Amy", "David", "Brian", "Jane"]
  8   print strings
  9   strings.sort( reverse=True)
 10   print strings
stdout:
[1, 2, 100, 20.5, 72, -6, 8, 26.300000000000001, 42, 77, 2]
[-6, 1, 2, 2, 8, 20.5, 26.300000000000001, 42, 72, 77, 100]

['John', 'Wendy', 'Amy', 'David', 'Brian', 'Jane']
['Wendy', 'John', 'Jane', 'David', 'Brian', 'Amy']
Doba běhu: 21.0 ms
Please note that the sorting is done in place replacing the old content of the list.
Sorting of more complicated sequence types is done in a item-by-item nature.
Expand/Shrink
Zdroj: (list5-2.py)
  1   lists = [[1, 2, 100],[20.5, 72], [-6, 8, 26.3], [1, 77, 2]]
  2   print lists
  3   lists.sort()
  4   print lists
  5   print
  6   
  7   tuples = [("John",1), ("Wendy",4), ("Amy",6), ("David",2), ("Brian",18), ("Jane",7)]
  8   print tuples
  9   tuples.sort()
 10   print tuples
 11   print
 12   
 13   inverse = [(6, 'Amy'), (18, 'Brian'), (2, 'David'), (7, 'Jane'), (1, 'John'), (4, 'Wendy')]
 14   print inverse
 15   inverse.sort()
 16   print inverse
 17   print
stdout:
[[1, 2, 100], [20.5, 72], [-6, 8, 26.300000000000001], [1, 77, 2]]
[[-6, 8, 26.300000000000001], [1, 2, 100], [1, 77, 2], [20.5, 72]]

[('John', 1), ('Wendy', 4), ('Amy', 6), ('David', 2), ('Brian', 18), ('Jane', 7)]
[('Amy', 6), ('Brian', 18), ('David', 2), ('Jane', 7), ('John', 1), ('Wendy', 4)]

[(6, 'Amy'), (18, 'Brian'), (2, 'David'), (7, 'Jane'), (1, 'John'), (4, 'Wendy')]
[(1, 'John'), (2, 'David'), (4, 'Wendy'), (6, 'Amy'), (7, 'Jane'), (18, 'Brian')]

Doba běhu: 21.5 ms