• python——元素列表基础


    元素列表:
    1在列表最后一位添加元素
    >>> number=[1,2,3,4,5]
    >>> number.append(6)
    >>> print(number)
    [1, 2, 3, 4, 5, 6]
    >>> number
    [1, 2, 3, 4, 5, 6]
    >>> number.extend([7,8,9])
    >>> number
    [1, 2, 3, 4, 5, 6, 7, 8, 9]


    2.在指定的位置添加元素
    >>> number.insert(1,0)
    >>> number
    [1, 0, 2, 3, 4, 5, 6, 7, 8, 9]

    3.输出指定位置的元素
    >>> name=['鸡蛋','水果','么么哒']

    >>> name[0]
    '鸡蛋'

    4.移除列表中指定的元素
    >>> name.remove ('鸡蛋')
    >>> name
    ['水果', '么么哒']


    移除列表中指定位置的元素
    >>> del name[1]
    >>> name
    ['水果']

    删除整个列表元素
    >>> del name
    >>> name


    5.弹出列表中最后一位的元素
    >>> name=['鸡蛋','鹅蛋','鸭蛋','你的']
    >>> name.pop()
    '你的'

    弹出列表中指定位置的元素
    >>> name.pop(0)
    '鸡蛋'


    6.列表分片:
    >>> name[0:1]
    ['鸡蛋']
    >>> name
    ['鸡蛋', '鸭蛋', '鹅蛋', '李狗蛋']
    >>> name[:1]
    ['鸡蛋']
    >>> name[:2]
    ['鸡蛋', '鸭蛋']
    >>> name[:4]
    ['鸡蛋', '鸭蛋', '鹅蛋', '李狗蛋']
    >>> name[1:]
    ['鸭蛋', '鹅蛋', '李狗蛋']
    >>> name[:]
    ['鸡蛋', '鸭蛋', '鹅蛋', '李狗蛋']

    7.特殊的列表:
    >>> list1=[1,2,3,4,5,6,7,8,9]
    >>> list1[0:9:2]
    [1, 3, 5, 7, 9]
    >>> list1[::2]
    [1, 3, 5, 7, 9]
    >>> list1[::-1]
    [9, 8, 7, 6, 5, 4, 3, 2, 1]

    >>> list=[123]
    >>> list*3
    [123, 123, 123]
    >>> 123 in list
    True
    >>> 1123 in list
    False

    8.列表中的列表:
    >>> list3=['小甲鱼','哈哈','嘻嘻','呵呵',['里','我的']]
    >>> '里' in list3
    False
    >>> '里' in list3[4]
    True


    9.计算参数在列表中的次数:
    >>> list1=[1,1,2,3,4,5,6,1,1,1]
    >>> list1.count(1)
    5

    10.返回参数在列表中的位置:
    >>> list1.index(2)
    2
    >>> list1.index(1)
    0

    11.返回列表中第二个指定参数的位置
    >>> list=[1,2,3,4,5,6,1]
    >>> list.index(1)
    0
    >>> start=list.index(1)+1
    >>> start
    1
    >>> stop=len(list)
    >>> stop
    7
    >>> list.index(1,start,stop)
    6


    12.反转整个列表:
    >>> list=[1,2,3,4,5,6,7]
    >>> list.reverse()
    >>> list
    [7, 6, 5, 4, 3, 2, 1]
    >>> list.reverse()
    >>> list
    [1, 2, 3, 4, 5, 6, 7]


    13.对列表进行排序,
    默认从小到大
    >>> list=[1,2,3,8,9,6,7,5,4]
    >>> list.sort()
    >>> list
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    从大到小:
    >>> list=[1,2,3,8,9,6,7,5,4]
    >>> list.sort(reverse=True)
    >>> list
    [9, 8, 7, 6, 5, 4, 3, 2, 1]


    14.拷贝列表和复制的区别:
    >>> list=[1,3,2,4,5,6]
    >>> list1=list[:]
    >>> list1
    [1, 3, 2, 4, 5, 6]
    >>> list2=list
    >>> list2
    [1, 3, 2, 4, 5, 6]
    >>> list.reverse()
    >>> list
    [6, 5, 4, 2, 3, 1]
    >>> list2
    [6, 5, 4, 2, 3, 1]
    >>> list1
    [1, 3, 2, 4, 5, 6]
    拷贝是将列表里的内容进行了拷贝,复制就是复制了列表,只要列表有变化,会一样变。

  • 相关阅读:
    P2634 [国家集训队]聪聪可可
    P2051 [AHOI2009]中国象棋
    java集成工具的简单总结
    java-web中的web.xml中的servlet和servlet-mapping标签,及网页处理流程
    ecplist中快速添加set get方法
    Spring创建容器之new ClassPathXmlApplicationContext错误
    设计模式之工厂模式
    java-web项目的eclipse里面引入jar包
    DES原理及代码实现
    Linux网络篇,ssh原理及应用
  • 原文地址:https://www.cnblogs.com/Leonardo-li/p/8665071.html
Copyright © 2020-2023  润新知