美文网首页
07-列表基础

07-列表基础

作者: shan317 | 来源:发表于2020-03-31 12:02 被阅读0次

    Python 列表也称为序列。
    列表中的每个元素都分配一个数字-它的位置或简称索引
    第一个索引 0,第二个索引 1, 以此类推

    • 索引是从0开始的
    # 定一个个列表
    list = [10, 20, 30, 'bob', 'alice', [1, 2, 3]]
    
    # 获取列表长度
    print(len(list))  # 6
    
    # 获取列表最后一项
    print(list[-1])  # [1, 2, 3]
    
    # 获取列表最后一项列表的长度
    print(list[-1][-1])  # 3
    
    # [1, 2, 3]是列表,[-1]表示获取列表最后一项
    print([1, 2, 3][-1]) # 3
    
    # 列表倒数第2项是字符串,再获取取出字符下标为2的字符
    print(list[-2][2])  # i
    
    print(list[3:5])   # ['bob', 'alice']
    
    print(10 in list)  # True
    
    print('o' in list)  # False
    
    print(100 not in list)  # True
    
    # 修改最后一项的值
    # list[-1] = 100
    print(list)  # [10, 20, 30, 'bob', 'alice', [1, 2, 3]]
    
    # 在列表末尾添加新的对象
    list.append('70')  
    print(list)  # [10, 20, 30, 'bob', 'alice', [1, 2, 3], '70']
    
    # 在列表末尾一次性追加另一个序列中的多个值
    list1 = [10, 33]
    list.extend(list1)
    print(list)  # [10, 20, 30, 'bob', 'alice', [1, 2, 3], 10, 33]
    
    # 将对象插入列表
    list.insert(0, 'Good')
    print(list)  # ['Good', 10, 20, 30, 'bob', 'alice', [1, 2, 3]]
    
    # 移除列表中某个值的第一个匹配项
    list.remove(10)
    print(list)  # [20, 30, 'bob', 'alice', [1, 2, 3]]
    
    
    # 用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数
    list2 = ['Google', 'Taobao', 'Facebook']
    list2.sort()
    print(list2)  # ['Facebook', 'Google', 'Taobao']
    
    

    相关文章

      网友评论

          本文标题:07-列表基础

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