python中的列表及numpy数组排序

一、列表排序 
# python中对列表排序有sort、sorted两种方法,其中sort是列表内置方法,其帮助文档如下:In [1]: help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

In [2]: help(list.sort)
Help on method_descriptor:
sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
# 一维列表排序a = [2,1,4,3,5]a.sort()         #[1, 2, 3, 4, 5]a.sort(reverse=True) #[5, 4, 3, 2, 1]# sorted()用法同sort(),不同点在于sorted()方法不影响原列表元素的顺序a = [2,1,4,3,5]b = sorted(a) # b: [1, 2, 3, 4, 5]a             # a: [2, 1, 4, 3, 5]
# 二维列表排序# 二维列表排序,可以设置sort()和sorted()方法的key关键字,通过lambda函数指定排序关键字a = [[1,‘b‘,5],[3,‘c‘,3],[5,‘a‘,4],[4,‘d‘,1],[2,‘f‘,2]]a.sort(key=(lambda x:x[0])) # [[1, ‘b‘, 5], [2, ‘f‘, 2], [3, ‘c‘, 3], [4, ‘d‘, 1], [5, ‘a‘, 4]]a.sort(key=(lambda x:x[1])) # [[5, ‘a‘, 4], [1, ‘b‘, 5], [3, ‘c‘, 3], [4, ‘d‘, 1], [2, ‘f‘, 2]]a.sort(key=(lambda x:x[0]),reverse=True) # reverse=True 按照x[0]降序排列 [[5, ‘a‘, 4], [4, ‘d‘, 1], [3, ‘c‘, 3], [2, ‘f‘, 2], [1, ‘b‘, 5]]

二、numpy数组排序

# numpy.sort()In [3]: help(np.sort)
Help on function sort in module numpy.core.fromnumeric:

sort(a, axis=-1, kind=‘quicksort‘, order=None)
    Return a sorted copy of an array.

    Parameters
    ----------
    a : array_like
        Array to be sorted.
    axis : int or None, optional
        Axis along which to sort. If None, the array is flattened before
        sorting. The default is -1, which sorts along the last axis.
    kind : {‘quicksort‘, ‘mergesort‘, ‘heapsort‘}, optional
        Sorting algorithm. Default is ‘quicksort‘.
    order : str or list of str, optional
        When `a` is an array with fields defined, this argument specifies
        which fields to compare first, second, etc.  A single field can
        be specified as a string, and not all fields need be specified,
        but unspecified fields will still be used, in the order in which
        they come up in the dtype, to break ties.

    Returns
    -------
    sorted_array : ndarray
        Array of the same type and shape as `a`.
In [4]: a
Out[1]:
array([[‘1‘, ‘b‘, ‘5‘],
       [‘3‘, ‘c‘, ‘3‘],
       [‘5‘, ‘a‘, ‘4‘],
       [‘4‘, ‘d‘, ‘1‘],
       [‘2‘, ‘f‘, ‘2‘]], dtype=‘<U11‘)

In [5]: np.sort(a,axis=0)  # axis=0 按列跨行排序
Out[2]:
array([[‘1‘, ‘a‘, ‘1‘],
       [‘2‘, ‘b‘, ‘2‘],
       [‘3‘, ‘c‘, ‘3‘],
       [‘4‘, ‘d‘, ‘4‘],
       [‘5‘, ‘f‘, ‘5‘]], dtype=‘<U11‘)

In [6]: np.sort(a,axis=1)  # axis=1 按行跨列排序
Out[3]:
array([[‘1‘, ‘5‘, ‘b‘],
       [‘3‘, ‘3‘, ‘c‘],
       [‘4‘, ‘5‘, ‘a‘],
       [‘1‘, ‘4‘, ‘d‘],
       [‘2‘, ‘2‘, ‘f‘]], dtype=‘<U11‘)

numpy中还有ndarray.sort()、argsort()和lexsort()方法,用到后再学习记录,待续……

原文地址:https://www.cnblogs.com/beikew/p/10246572.html

时间: 2025-01-07 09:42:40

python中的列表及numpy数组排序的相关文章

Python中的列表,元组,字符串之间的相互转化

Python中的列表元组和字符串之间的相互转化需要利用,tuple(),list(),str(). 示例如下: >>> the_string = "hello I'am xiaoli!" >>> #字符串转化为元组 >>> the_tuple = tuple(the_string) >>> the_tuple ('h', 'e', 'l', 'l', 'o', ' ', 'I', "'", 'a

Python 中使用列表解析时候的区别

使用[] + for语句是解析列表 而使用() + for语句是产生生成器 实例代码如下: alist = [1, 2, 3, 4, 5] another_list = [i for i in alist] print another_list a_generator = (i for i in alist) print a_generator for i in a_generator: print i Python 中使用列表解析时候的区别

Python中的列表解析和生成器表达式

Python中的列表解析和生成器表达式 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.列表解析案例 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 #@author :yinzhengjie 4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/

关于Python中的列表理解及用法

在Python中,列表理解通常用于编写单行语句,这些语句通过可迭代对象进行迭代以创建新的列表或字典.本文首先介绍for循环如何在Python中工作,然后解释如何在Python中使用列表理解. Python中的for循环 Python中的for循环语句按顺序遍历任何对象.列表.字符串等的成员.与其他编程语言相比,它的语法更加简洁,不需要手工定义迭代步骤,也不需要开始迭代.尽管有几种方法可以使它的行为与其他编程语言相同(本文将不详细讨论).还可以使用continue.break.pass等语句控制f

12.python中的列表

列表和元祖最大的不同就是列表是可以修改的. 老规矩,先使用 help(list) ,真的是 help() 大法好呀. 好,来人,上代码. Help on class list in module __builtin__: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | |

python中的列表

1. python中列表的概念 列表即以“[]”框起来的一组数据,数据可以为不同的类型,也可以为空. >>> nums = [1,2,3.0,5e2,'ginson'] >>> print(nums) [1, 2, 3.0, 500.0, 'ginson'] 2. 向列表中添加数据. ① append,向列表中添加元素,默认添加到列表尾部. >>> nums.append(‘林间’) >>> nums [1,2,3.0,500.0,'

Python学习笔记整理(五)Python中的列表.

列表和字段,这两种类型几乎是Python所有脚本的主要工作组件.他们都可以在原处进行修改,可以按需求增加或缩短,而且包含任何种类的对象或者被嵌套. 一.列表 列表的主要属性: *任意对象的有序集合 从功能上看,列表就是收集其他对象的地方,可以把它看作组.列表所包含每一项都保持了从左到右的位置顺序(它们是序列) *通过偏移读取 和字符串一样,可以通过列表对象的偏移对其进行索引,从而读取对象的某一部分内容.可以自行分片和合并之类的任务. *可变长度,异构以及任意嵌套 列表可以实地增长或者缩短,并且可

python中的列表3

一.列表的一些常用操作符 1.比较操作符 当列表中有多个元素时,列表间只比较第0个元素. >>> list1 = [1,2] >>> list2 = [2,1] >>> list1 > list2 False 2.逻辑操作符 >>> list1 = [1,2] >>> list2 = [2,1] >>> list3 = [1,2] >>> (list1 < list2)

python中的列表和元组

列表:list 元组:tuple 列表是python中常用的数据类型,通过列表可以实现对数据的存储.修改. 列表的定义: name_list = ['apple','orange','grape','pear','barry'] 可以通过下标访问列表中的元素,下标从0开始 切片:取多个元素 追加: 插入: 修改: 删除[3种方法] 扩展 拷贝[拷贝分为浅拷贝  和  深拷贝] 统计 排序&翻转 [说明:3.0里不同数据类型不能放在一起排序了] 获取下标: 获取下标index方法如下: 元组:元组