• 列表


    一.列表

    1.作用:按位置存放多个值

    2.定义

    L=[1,2,’a’,[123,456]]

    3.类型转换

    res=list('hello')
    print(res)
    #['h', 'e', 'l', 'l', 'o']
    res=list({'k1':111,'k2':222,'k3':3333})
    print(res)
    #['k1', 'k2', 'k3']

    二.列表的索引

    l=['111','222','333']

    1.正向取

    l[0]----->’111’

    2.反向取

    l[-1]----->’333’

    ps:列表可以通过索引取,也可以改,但是无法通过索引新增。


    三.列表的切片(顾头不顾尾,步长)

    l = [111, 'egon', 'hello', 'a', 'b', 'c', 'd', [1, 2, 3]]
    print(l[0:3])------>[111, 'egon', 'hello']
    print(l[0:5:2]) ----->[111, 'hello', 'b']
    ps:列表切片得到列表,等同于拷贝行为,而且相当于浅copy。

    四.列表的追加

    1.append(在末尾追加)
    a='1230'
    l=['111','222','333']
    l.append(a)
    print(l)
    #['111', '222', '333', '1230']
    2.insert(在指定位置插入)
    l=['111','222','333']
    l.insert(0,'abcd')
    print(l)
    #['abcd', '111', '222', '333']
    3.extend(依次添加值)
    l=['111','222','333']
    a='1234'
    l.extend(a)
    print(l)
    #['111', '222', '333', '1', '2', '3', '4']

    五.列表的删除

    1.del(没有返回值)

    l=['111','222','333']
    del l[0]
    print(l)
    #['222', '333']
    #ps:del没有返回值

    2.pop(删除并返回改值)

    l=['111','222','333']
    a=l.pop(0)
    print(a)
    #‘111’

    3.remove(删除指定值,返回None)

    l=['111','222','333']
    a=l.remove('333')
    print(l,a)
    #['111', '222'] None

    六.列表的长度

    print(len([1, 2, 3])) #3

    七.成员运算in和not in

    print('aaa' in ['aaa', 1, 2]) #True
    print(1 in ['aaa', 1, 2]) #True

    八.列表的常用方法

    1.count()#统计列表中某种元素个个数
    l=['111','222','333','111']
    print(l.count('111')) #2
    2.index()#索引某个值并返回索引值
    l=['111','222','333']
    print(l.index('111')) #0
    3.clear()#清楚列表
    l=['111','222','333']
    l.clear()
    print(l) #[]
    4.reverse()#不是排序,就是将列表倒过来
    l = [1, 'egon','alex','lxx']
    l.reverse()
    print(l)
    #['lxx', 'alex', 'egon', 1]
    5.sort()#列表内元素必须是同种类型才可以排序
    ps:字符串也适用,按照ASCII码表对比。
    l=[11,-3,9,2,3.1]
    l.sort() # 默认从小到大排,称之为升序
    print(l)
    #[-3, 2, 3.1, 9, 11]
    l.sort(reverse=True) # 从大到小排,设置为降序
    print(l)
    #[11, 9, 3.1, 2, -3]

    九.补充

    1、队列:FIFO,先进先出
    l=[]
    # 入队操作
    l.append('first')
    l.append('second')
    l.append('third')
    print(l)
    #['first', 'second', 'third']
    # 出队操作
    print(l.pop(0)) #first
    print(l.pop(0)) #second
    print(l.pop(0)) #third
    2、堆栈:LIFO,后进先出
    l=[]
    # 入栈操作
    l.append('first')
    l.append('second')
    l.append('third')
    print(l)
    #['first', 'second', 'third']
    # 出队操作
    print(l.pop()) #third
    print(l.pop()) #second
    print(l.pop()) #first


  • 相关阅读:
    HTML和CSS 基本要点必看
    CSS
    六个选择器
    HTML初级课程 (自学可懂)
    this
    1.作用域链
    js if 语句
    js数据类型
    ifelse语句
    三元运算符
  • 原文地址:https://www.cnblogs.com/bailongcaptain/p/12482331.html
Copyright © 2020-2023  润新知