📜  如何在Python对一组值进行排序?

📅  最后修改于: 2021-04-26 19:08:15             🧑  作者: Mango

排序是指以递增或递减的方式排列一组值。 Python有多种对值进行排序的方法。我们可以使用各种数据结构(例如列表,元组,字典)存储一组或一组值,这取决于我们存储的数据。因此,在本文中,我们将讨论一些在Python对数据进行排序的方法和标准。

Sorted()方法

这是Python的预定义方法,可以对任何类型的对象进行排序。

句法:

sorted(iterable, key, reverse)

在此方法中,我们传递了3个参数,其中2个(键和反向键)是可选的,第一个参数(即iterable)可以是任何可迭代的对象。此方法返回排序列表,但不更改原始数据结构。

范例1:

Python3
# List
list_of_items = ['g', 'e', 'e', 'k', 's']
print(sorted(list_of_items))
  
# Tuple
tuple_of_items = ('g', 'e', 'e', 'k', 's')
print(sorted(tuple_of_items))
  
# String-sorted based on ASCII 
# translations
string = "geeks"
print(sorted(string))
  
# Dictionary
dictionary = {'g': 1, 'e': 2, 'k': 3, 's': 4}
print(sorted(dictionary))
  
# Set
set_of_values = {'g', 'e', 'e', 'k', 's'}
print(sorted(set_of_values))
  
# Frozen Set
frozen_set = frozenset(('g', 'e', 'e', 'k', 's'))
print(sorted(frozen_set))


Python3
# using key parameter with pre-defined
# function i.e. len()
  
list_of_items = ["apple", "ball", "cat", "dog"]
  
print("Sorting without key parameter:", sorted(list_of_items))
print("Sorting with len as key parameter:", sorted(list_of_items, key=len))


Python3
# using key parameter with user-defined 
# function i.e. by_name
# using key parameter with user-defined 
# function i.e. by_marks
  
# here is a list_of_tuples where the first
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh",56),("Reka",54),("Lasya",32),("Amar",89)]
  
# defining a user-defined function which returns
# the first item(name) 
def by_name(ele):
  return ele[0]
  
# defining a user-defined function which returns 
# the second item(marks) 
def by_marks(ele):
  return ele[1]
  
print("Sorting without key parameter:", sorted(list_of_items))
  
print("Sorting with by_name as key parameter:", 
      sorted(list_of_items, key=by_name))
  
print("Sorting with by_marks as key parameter:", 
      sorted(list_of_items, key=by_marks))


Python3
# using key parameter reverse
  
list_of_items = ["geeks","for","geeks"]
  
print("Sorting without key parameter:",
      sorted(list_of_items))
  
print("Sorting with len as key parameter:",
      sorted(list_of_items, reverse=True))


Python3
# using by_name and by_marks as key parameter
# and making reverse parameter true
  
# here is a list_of_tuples where the first
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh", 56), ("Reka", 54), 
                 ("Lasya", 32), ("Amar", 89)]
  
# defining a user-defined function which
# returns the first item(name)
def by_name(ele):
    return ele[0]
  
# defining a user-defined function which 
# returns the second item(marks)
def by_marks(ele):
    return ele[1]
  
print("Sorting without key and reverse:", sorted(list_of_items))
  
print("Sorting with by_name as key parameter and reverse parameter as False:",
      sorted(list_of_items, key=by_name, reverse=False))
print("Sorting with by_name as key parameter and reverse parameter as True:",
      sorted(list_of_items, key=by_name, reverse=True))
  
print("Sorting with by_marks as key parameter and reverse parameter as False:",
      sorted(list_of_items, key=by_marks, reverse=False))
print("Sorting with by_marks as key parameter and reverse parameter as True:",
      sorted(list_of_items, key=by_marks, reverse=True))


Python3
# creating a list of items
list_of_items = ["geeks", "for", "geeks"]
print("Original list:", list_of_items)
  
# using the sort method to sort 
# the items
list_of_items.sort()
  
# displaying the list
print("Sorted list:", list_of_items)


Python3
# using key parameter with pre-defined
# function i.e. len()
  
list_of_items = ["apple", "ball", "cat", "dog"]
  
print("Orginal List:", list_of_items)
  
# using the len() as key parameter and
# sorting the list
list_of_items.sort(key=len)
print("Sorting with len as key parameter:", list_of_items)


Python3
# using key parameter with user-defined
# function i.e. by_name
# using key parameter with user-defined
# function i.e. by_marks
  
# defining a user-defined function which 
# returns the first item(name)
def by_name(ele):
    return ele[0]
  
# defining a user-defined function which 
# returns the second item(marks)
def by_marks(ele):
    return ele[1]
  
  
# here is a list_of_tuples where the first
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh", 56), ("Reka", 54), 
                 ("Lasya", 32), ("Amar", 89)]
print("original list:", list_of_items)
  
# sorting by key value as by_name function
list_of_items.sort(key=by_name)
print("Sorting with by_name as key parameter:", list_of_items)
  
# here is a list_of_tuples where the first 
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh", 56), ("Reka", 54),
                 ("Lasya", 32), ("Amar", 89)]
print("original list:", list_of_items)
  
# sorting by key value as by_marks function
list_of_items.sort(key=by_marks)
print("Sorting with by_marks as key parameter:", list_of_items)


Python3
# using key parameter reverse
  
list_of_items = ["geeks", "for", "geeks"]
  
print("original list:", list_of_items)
  
list_of_items.sort(reverse=True)
print("sorting with reverse parameter", list_of_items)


输出
['e', 'e', 'g', 'k', 's']
['e', 'e', 'g', 'k', 's']
['e', 'e', 'g', 'k', 's']
['e', 'g', 'k', 's']
['e', 'g', 'k', 's']
['e', 'g', 'k', 's']

范例2:

使用预定义函数作为键参数。因此,第二个参数(即key )用于通过某些预定义函数(例如len()或某些用户定义函数)对给定的数据结构进行排序。它根据传递给key参数的函数对数据结构中的值进行排序。

Python3

# using key parameter with pre-defined
# function i.e. len()
  
list_of_items = ["apple", "ball", "cat", "dog"]
  
print("Sorting without key parameter:", sorted(list_of_items))
print("Sorting with len as key parameter:", sorted(list_of_items, key=len))
输出
Sorting without key parameter: ['apple', 'ball', 'cat', 'dog']
Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']

范例3:

对键参数使用用户定义的函数。

Python3

# using key parameter with user-defined 
# function i.e. by_name
# using key parameter with user-defined 
# function i.e. by_marks
  
# here is a list_of_tuples where the first
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh",56),("Reka",54),("Lasya",32),("Amar",89)]
  
# defining a user-defined function which returns
# the first item(name) 
def by_name(ele):
  return ele[0]
  
# defining a user-defined function which returns 
# the second item(marks) 
def by_marks(ele):
  return ele[1]
  
print("Sorting without key parameter:", sorted(list_of_items))
  
print("Sorting with by_name as key parameter:", 
      sorted(list_of_items, key=by_name))
  
print("Sorting with by_marks as key parameter:", 
      sorted(list_of_items, key=by_marks))

输出

范例4:

因此,第三个参数是反向的,用于按降序或降序对可迭代对象进行排序。

Python3

# using key parameter reverse
  
list_of_items = ["geeks","for","geeks"]
  
print("Sorting without key parameter:",
      sorted(list_of_items))
  
print("Sorting with len as key parameter:",
      sorted(list_of_items, reverse=True))
输出
Sorting without key parameter: ['for', 'geeks', 'geeks']
Sorting with len as key parameter: ['geeks', 'geeks', 'for']

范例5:

使用所有三个参数

Python3

# using by_name and by_marks as key parameter
# and making reverse parameter true
  
# here is a list_of_tuples where the first
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh", 56), ("Reka", 54), 
                 ("Lasya", 32), ("Amar", 89)]
  
# defining a user-defined function which
# returns the first item(name)
def by_name(ele):
    return ele[0]
  
# defining a user-defined function which 
# returns the second item(marks)
def by_marks(ele):
    return ele[1]
  
print("Sorting without key and reverse:", sorted(list_of_items))
  
print("Sorting with by_name as key parameter and reverse parameter as False:",
      sorted(list_of_items, key=by_name, reverse=False))
print("Sorting with by_name as key parameter and reverse parameter as True:",
      sorted(list_of_items, key=by_name, reverse=True))
  
print("Sorting with by_marks as key parameter and reverse parameter as False:",
      sorted(list_of_items, key=by_marks, reverse=False))
print("Sorting with by_marks as key parameter and reverse parameter as True:",
      sorted(list_of_items, key=by_marks, reverse=True))

输出

Sort()方法

默认情况下,此方法以升序对列表进行排序,我们可以使用反向参数以降序进行排序。此方法更改原始列表,并且不返回任何内容。

范例1:

Python3

# creating a list of items
list_of_items = ["geeks", "for", "geeks"]
print("Original list:", list_of_items)
  
# using the sort method to sort 
# the items
list_of_items.sort()
  
# displaying the list
print("Sorted list:", list_of_items)
输出
Original list: ['geeks', 'for', 'geeks']
Sorted list: ['for', 'geeks', 'geeks']

范例2:

使用预定义函数作为关键参数

Python3

# using key parameter with pre-defined
# function i.e. len()
  
list_of_items = ["apple", "ball", "cat", "dog"]
  
print("Orginal List:", list_of_items)
  
# using the len() as key parameter and
# sorting the list
list_of_items.sort(key=len)
print("Sorting with len as key parameter:", list_of_items)
输出
Orginal List: ['apple', 'ball', 'cat', 'dog']
Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']

范例3:

使用用户定义的函数作为关键参数

Python3

# using key parameter with user-defined
# function i.e. by_name
# using key parameter with user-defined
# function i.e. by_marks
  
# defining a user-defined function which 
# returns the first item(name)
def by_name(ele):
    return ele[0]
  
# defining a user-defined function which 
# returns the second item(marks)
def by_marks(ele):
    return ele[1]
  
  
# here is a list_of_tuples where the first
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh", 56), ("Reka", 54), 
                 ("Lasya", 32), ("Amar", 89)]
print("original list:", list_of_items)
  
# sorting by key value as by_name function
list_of_items.sort(key=by_name)
print("Sorting with by_name as key parameter:", list_of_items)
  
# here is a list_of_tuples where the first 
# item in tuple is the student name and the
# second item is his/her marks
list_of_items = [("Ramesh", 56), ("Reka", 54),
                 ("Lasya", 32), ("Amar", 89)]
print("original list:", list_of_items)
  
# sorting by key value as by_marks function
list_of_items.sort(key=by_marks)
print("Sorting with by_marks as key parameter:", list_of_items)

输出

范例4:

使用反向参数

Python3

# using key parameter reverse
  
list_of_items = ["geeks", "for", "geeks"]
  
print("original list:", list_of_items)
  
list_of_items.sort(reverse=True)
print("sorting with reverse parameter", list_of_items)
输出
original list: ['geeks', 'for', 'geeks']
sorting with reverse parameter ['geeks', 'geeks', 'for']