程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3 learning notes -- two sorting methods

編輯:Python

python3 Learning notes -- Two sort methods

  • List sorting method
  • sort()
  • sorted()

List sorting method

  • sort(): Only on list Object to sort , Will change list Self order , no return value , namely In situ sorting
  • sorted(): Sort all iteratable objects , Return the sorted new object , The original object remains unchanged ;

sort()

list.sort(key=None, reverse=False)

  • key: Set sorting method , Or specify list Elements used for sorting in ;
  • reverse: Ascending descending order , The default is ascending ;

Example :

nums = [2, 3, 5, 1, 6]
nums.sort()
print(nums) # [1, 2, 3, 5, 6]
nums.sort(key=None, reverse=True)
print(nums) # [6, 5, 3, 2, 1]
students = [('john', 'C', 15), ('jane', 'A', 12), ('dave', 'B', 10)]
students.sort(key=lambda x: x[2]) # Sort by the third element in the list 
print(students) # [('dave', 'B', 10), ('jane', 'A', 12), ('john', 'C', 15)]

sorted()

sorted(iterable [, key[, reverse]])

  • key : Set sorting method , Or specify in the iteration object , Elements for sorting ;
  • reverse : Ascending descending order , The default is ascending ;

Example :

nums = [2, 3, 5, 1, 6]
newNums = sorted(nums)
print(nums) # [2, 3, 5, 1, 6]
print(newNums) # [1, 2, 3, 5, 6]
students = [('john', 'C', 15), ('jane', 'A', 12), ('dave', 'B', 10)]
newStudents = sorted(students, key=lambda x: x[1])
print(students) # [('john', 'C', 15), ('jane', 'A', 12), ('dave', 'B', 10)]
print(newStudents) # [('jane', 'A', 12), ('dave', 'B', 10), ('john', 'C', 15)]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved