美文网首页
list列表

list列表

作者: 圣堂刺客_x | 来源:发表于2019-10-22 20:16 被阅读0次

    1. sort()方法 对原列表进行排序

    描述
    sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
    语法

    list.sort( key=None, reverse=False)
    

    参数
    key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
    reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
    返回值
    该方法没有返回值,但是会对列表对象进行排序。
    实例
    以下实例展示了 sort() 函数的使用方法:

    1、方法没有返回值,对原列表对象进行排序
    >>> aList = ['Google', 'Runoob', 'Taobao', 'Facebook']
    >>> aList.sort()
    >>> aList
    ['Facebook', 'Google', 'Runoob', 'Taobao']
    
    2、reverse = True 降序, reverse = False 升序(默认)
    >>> aList.sort(reverse=False)
    >>> aList
    ['Facebook', 'Google', 'Runoob', 'Taobao']
    >>> aList.sort(reverse=True)
    >>> aList
    ['Taobao', 'Runoob', 'Google', 'Facebook']
    >>>
    
    3、根据自定义规则来排序,使用参数:key,使用key,默认搭配lambda函数
    
    (1)根据元素长度排序
    >>> chars = ['a', 'is', 'boy', 'bruce', 'handsome']
    >>> chars.sort(key=lambda x:len(x))
    >>> chars
    ['a', 'is', 'boy', 'bruce', 'handsome']
    >>> #特殊写法
    >>> chars.sort(key=len)
    >>> chars
    ['a', 'is', 'boy', 'bruce', 'handsome']
    >>>
    
    (2)对元组构成的列表进行排序
    >>> tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
    >>> tuple_list.sort(key=lambda x:x[0])
    >>> tuple_list
    [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]
    
    (3)根据自定义规则排序
    ex1:
    >>> list_num = [1,-2,-3,4,-5]
    >>> list_num.sort(key=lambda x:x**2)
    >>> list_num
    [1, -2, -3, 4, -5]
    
    ex2:
    
    >>> def takeSecond(elem):
    ...     return elem[1]
    ...
    >>> r = [(2, 2), (3, 4), (4, 1), (1, 3)]
    >>> r.sort(key=takeSecond)
    >>> r
    [(4, 1), (2, 2), (1, 3), (3, 4)]
    >>>
    

    2. remove() 移除列表中某个值的第一个匹配项

    描述
    remove() 函数用于移除列表中某个值的第一个匹配项。
    语法

    list.remove(obj)
    

    参数
    obj -- 列表中要移除的对象。
    返回值
    该方法没有返回值但是会移除列表中的某个值的第一个匹配项。
    实例
    以下实例展示了 remove()函数的使用方法:

    >>> aList = [123, 'xyz', 'zara', 'abc', 'xyz']
    >>> aList.remove('xyz')
    >>> aList
    [123, 'zara', 'abc', 'xyz']
    >>> aList.remove('abc')
    >>> aList
    [123, 'zara', 'xyz']
    

    3. index() 列表中找出某个值第一个匹配项的索引位置

    描述
    index() 函数用于从列表中找出某个值第一个匹配项的索引位置。
    语法

    list.index(x[, start[, end]])
    

    参数
    x-- 查找的对象。
    start-- 可选,查找的起始位置。
    end-- 可选,查找的结束位置。
    返回值
    该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。
    实例
    以下实例展示了 index()函数的使用方法:

    >>> aList = [123, 'xyz', 'runoob', 'abc']
    >>> aList.index('abc')
    3
    >>> aList.index('xyz')
    1
    >>>
    

    相关文章

      网友评论

          本文标题:list列表

          本文链接:https://www.haomeiwen.com/subject/wtfwuctx.html