zoukankan      html  css  js  c++  java
  • Python列表

    获取列表元素

    下标取值,下标从0开始:

    spam = ['cat', 'bat', 'rat', 'elephant']
    print(spam[0])  # cat
    print(spam[1])  # bat
    print(spam[2])  # rat
    print(spam[3])  # elephant
    

    负数下标

    整数值-1指的是列表中最后一个下标,-2指的是倒数第二个下标。

    获取列表长度

    spam = ['cat', 'dog', 'moose']
    print(len(spam))
    

    获取子列表

    spam = ['cat', 'bat', 'rat', 'elephant']
    print(spam[2:3])  # ['rat']
    print(spam[2:])   # ['rat', 'elephant']
    print(spam[:2])   # ['cat', 'bat']
    

    截取子列表时,下表从0开始,左开右闭

    连接列表

    使用 + 连接列表:

    spam = [1, 2, 3] + ['A', 'B', 'C']
    print(spam)  # [1, 2, 3, 'A', 'B', 'C']
    

    删除列表元素

    spam = ['cat', 'bat', 'rat', 'elephant']
    del spam[2]
    print(spam)
    

    遍历列表

    spam = ['cat', 'bat', 'rat', 'elephant']
    for val in spam:
        print(val)
    

    表中被删除值后面的所有值,都将向前移动一个下标

    判断一个值是否在列表中

    spam = ['cat', 'bat', 'rat', 'elephant']
    print('cat' in spam)       # True
    print('dog' in spam)       # False
    print('bat' not in spam)   # False
    

    获取指定值的下标

    spam = ['cat', 'bat', 'rat', 'elephant', 'rat']
    print(spam.index('rat'))  # 2
    print(spam.index('dog'))  # ValueError: 'dog' is not in list
    

    如果值不在列表中,报错ValueError,如果值存在列表中,返回它的下标,如果存在重复值,返回第一次出现的下标。

    向列表中插入值

    spam = ['cat', 'dog', 'bat']
    spam.append('moose')
    print(spam)  # ['cat', 'dog', 'bat', 'moose']
    spam.insert(1, 'chicken')
    print(spam)  # ['cat', 'chicken', 'dog', 'bat', 'moose']
    

    使用remove方法从列表中删除值

    spam = ['cat', 'dog', 'bat', 'dog']
    spam.remove('dog')
    print(spam)             # ['cat', 'bat', 'dog']
    spam.remove('chicken')  # ValueError: list.remove(x): x not in list
    

    给remove方法传入一个值,如果列表中存在,它将会从被调用的列表中删除,如果列表中存在多个相同值,删除第一次出现的值,如果列表中不存在,报错ValueError。

    列表排序

    spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
    spam.sort()              # 默认排序,从小到大
    print(spam)
    spam.sort(reverse=True)  # 逆序排序
    print(spam)
    spam.sort(key=str.lower) # 排序时不区分大小写
    

    数值列表或字符串列表可以使用sort方法排序,数值字符串混合列表调用sort方法,python2可以执行,python3报错TypeError。

    深拷贝

    将列表变量赋值给另一个变量,实际上是将列表的引用赋值给了该变量,要对列表进行深拷贝,可以使用copy模块。

    import copy
    
    spam = ['A', 'B', 'C', 'D']
    cheese = copy.copy(spam)        # 深拷贝
    
    spam2 = ['A', 'B', 'C', ['D', 'E']]
    cheese2 = copy.deepcopy(spam2)  # 如果要拷贝的列表包含了列表,使用deepcopy
    

    元组与列表的区别

    元组输入时用(),列表用[]

    元组是不可变的,不能让它们的值被修改、添加或删除

    如果元组只有一个值,在括号内该值的后面跟上一个逗号,表明这是一个元组

    eggs = ('hello', 42, 0.5)
    print(eggs[0])    # 'hello'
    print(eggs[1:3])  # (42, 0.5)
    
  • 相关阅读:
    递推2 2046
    递推思想
    acm2047
    杭电ACM2043
    判断a=b?
    将一列字段用逗号分隔开,作为一个显示
    MESQL 数据误操作,恢复数据方法
    有两个frame,在一个frame中获取另一个frame中元素的值
    饼状图显示各类别展示所占百分比
    winfrom中的webbrowser内核版本修改
  • 原文地址:https://www.cnblogs.com/zhouzl/p/11002789.html
Copyright © 2011-2022 走看看