排序sort(),sorted(),argsort()傻傻分不清

我们经常遇到排序的问题,而Python处理排序问题时经常使用以下的三个函数,sort(),sorted(),argsort().

list.sort()和sorted()均为Python的内建函数

sort函数的帮助:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1

sort排序时是在原列表中直接排序既改变了原来的列表。

sorted函数的帮助:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

我们可以发现sorted函数是新建一个列表既原列表不动,新增加一个排好序的列表

argsort的帮助文档:

argsort(a, axis=-1, kind='quicksort', order=None)
    Returns the indices that would sort an array.
    
    Perform an indirect sort along the given axis using the algorithm specified
    by the `kind` keyword. It returns an array of indices of the same shape as
    `a` that index data along the given axis in sorted order.

argsort()是numpy包下的一个函数,他的返回值是排序的索引值

Demo:

import numpy as np  

a = [1,1,2,2,2,33,5,6,7]

b = sorted(a)		# 列表a没有改变,列表b为列表a排序的结果
c = np.argsort(a)   # 列表a没有改变,返回的值是排序结果的索引

print a,b,c

a.sort()			# 列表a发生改变
print a

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值