zoukankan      html  css  js  c++  java
  • Python的一些列表方法

    1.append:方法append用于将一个对象附加到列表末尾,直接修改列表

    lst=[1,2,3,4]
    lst.append(5)
    print(lst)  1,2,3,4,5

    2.clear:方法clear清空列表内容,类似切片赋值语句lst[:]=[]

    lst=[1,2,3]
    print(lst)    1,2,3
    print(lst.clear())    none

    3.copy:复制列表

    a=[1,2,3]
    b=a.copy()
    b[1]=4
    print(a)  1,2,3
    print(b)  1,4,3

    4.count:计算指定元素在列表中出现了多少次

    x=[1,2,3,3,2,5,[2,3],[2,3,[2,3]]]
    print(x.count(3))  2
    print(x.count([2,3]))  1

     5.extend:方法extend让你能够使用一个列表来扩展另一个列表

    a=[1,2,3]
    b=[4,5,6]
    a.extend(b)
    print(a)  1,2,3,4,5,6

    6.index:方法index在列表中查找指定值第一次出现的索引

    str=['you','we','she']
    print(str.index('you')    0

    7.insert:方法insert将一个对象插入列表中

    str=['you','we','she']
    str.insert(1,'he')
    print(str)    ['you', 'he', 'we', 'she']

    8.pop:方法pop删除列表中一个元素(若未指定,则为最后一个元素),并返回这一元素,pop是唯一既修改列表又返回一个非none值的列表方法

    num=[1,2,3,4,5]
    print(num.pop())    5
    print(num)    [1, 2, 3, 4]
    print(num.pop(2))   3
    print(num)   [1, 2, 4]

    9.remove:方法remove删除第一个为指定值的元素

    str=['she','he','it','you']
    str.remove('it')
    print(str)    ['she', 'he', 'you']

    10.reverse:方法reverse按相反的顺序排列列表中的元素

    x=[1,2,3,7,6,5]
    x.reverse()
    print(x)    [5, 6, 7, 3, 2, 1]

    11.sort:方法sort用于对列表排序:可接受两个可选参数:key和reverse,可将参数key设置为函数,根据key进行排序,参数reverse指出是否按相反的顺序进行排序

    x=[1,4,6,8,2,6]
    x.sort();
    print(x)    [1, 2, 4, 6, 6, 8]
    x=['add','append','sort','sorted']
    x.sort(key=len)
    print(x)    ['add', 'sort', 'append', 'sorted']
    
    x=['add','append','sort','sorted']
    x.sort(key=len,reverse=True)
    print(x)
  • 相关阅读:
    [ 基础 转义字符 ] HTML转义字符对照表
    CRM 启用或禁用自定义代码执行
    CRM Setstate plugin
    CRM HomePage.aspx
    CRM 403错误
    CRM 2016 js 奇怪现象
    CRM 日期类型的一些处理JS
    CRM JS 设置lookup字段 setSimpleLookupValue
    CRM 2016 级联过滤 类比省市县
    CRM合并事件
  • 原文地址:https://www.cnblogs.com/qc-wh/p/10740411.html
Copyright © 2011-2022 走看看