[python] list.sort and sorted

本文深入讲解了Python中两种主要的排序方法:sorted()函数和list.sort()方法。详细对比了它们的功能、用法及效率差异,并通过实例演示如何对列表和字典进行排序。

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.

  • sorted accept 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) where eis an element of dict.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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值