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

List in Python What is the difference between sort() and sorted()?

編輯:Python

Python Provides two ways to sort lists , Built in list method list.sort() And built-in functions sorted(). Although both will sort the elements of the list , But if you don't use it properly , They may produce unexpected or undesirable results .

similarities and differences

The main difference between the two is list.sort() The list will be sorted in place , Change its index and return None, and sorted() A new sort list will be returned , The original list remains unchanged . Another difference is sorted() Accept any iteratable whilelist.sort() yes list Class method , And can only be used with lists .

nums = [2, 3, 1, 5, 6, 4, 0]
print(sorted(nums)) # [0, 1, 2, 3, 4, 5, 6]
print(nums) # [2, 3, 1, 5, 6, 4, 0]
print(nums.sort()) # None
print(nums) # [0, 1, 2, 3, 4, 5, 6]

both list.sort() and sorted() All have the same key Optional reverse Parameters , And you can call... On each list element before comparing .

When to use each

list.sort() It should be used when you want to change the list and do not need to retrieve the original order of the elements . On the other hand ,sorted() When the object to be sorted is an iteratable object ( For example, a list of 、 Tuples 、 Dictionaries 、 character string ) And the expected result is a sorted list of all elements , It should be used .


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