1. sorted and list.sort
Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.
sortedaccept any interable.list.sort()is only defined for list
Note that list.sort() will change the original list. If you will use the original list again, please use sorted. But if you will not use the original list, list.sort() is more efficient
1. sorted
Useage of sorted:
sorted(iterable[, cmp[, key[, reverse]]]) --> new sorted list
iterable: return a new sorted list from the items in iterable.- any type of sequence: list, str, tuple…
- some type of non-sequence: dict, file…
- any object defined using
_iter_or_getitem_
cmp: specifies a custom comparison function of two arguments (iterable elements), which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()).key: specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower.reverse: default = false, which means sorting increasingly.
2.1 sorted list
Example:
>>> mylist = [1,4,2,6,5]
>>> newlist1 = sorted(mylist)
>>> newlist1
[1, 2, 4, 5, 6]
>>> mylist
[1, 4, 2, 6, 5]
>>> newlist2 = sorted(mylist, reverse=True)
>>> newlist2
[6, 5, 4, 2, 1]
2.2 sorted dictionary
Common usage:
sorted(dict.items(), key=lambda e:e[1], reverse=True)whereeis an element ofdict.items(). ```e[0]` means sorting by key ande[1]“ means sorting by value.
# use key
>>> mydict = {"Lucy":11, "Lily":16, "LiMei":9}
>>> sorted(mydict.items(), key=lambda e:e[1])# sort by value
[('LiMei', 9), ('Lucy', 11), ('Lily', 16)]
# use cmp
>>> sorted(mydict.items(), cmp=lambda x,y: cmp(x[1],y[1]))# sort by value
[('LiMei', 9), ('Lucy', 11), ('Lily', 16)]
We can use operator to make sort faster.
import operator
- operator.itemgetter(1)
# use operator
>>> sorted(mydict.items(), key=operator.itemgetter(1))
[('LiMei', 9), ('Lucy', 11), ('Lily', 16)]
Note: return a list of tuple because mylist.items()gives a list of tuples.
2. list.sort()
Example:
>>> mylist = [1,4,2,6,5]
>>> mylist.sort()
>>> mylist
[1, 2, 4, 5, 6]
Note original list changed
本文深入讲解了Python中两种主要的排序方法:sorted()函数和list.sort()方法。详细对比了它们的功能、用法及效率差异,并通过实例演示如何对列表和字典进行排序。
3597

被折叠的 条评论
为什么被折叠?



