• python之列表【list】


    使用下面这个列表进行演示

    test_list = ["a",1,"b","c",2,3,4]
    

    # 1、append

    # 在list尾部添加元素
    test_list.append("str")
    print(test_list)
    # ['a', 1, 'b', 'c', 2, 3, 4, 'str']
    




    # 2、clear

    # 清空list
    test_list.clear()
    
    print(test_list)
    
    # []
    



    # 3、copy

    # 拷贝一个列表,这个拷贝是一个深拷贝,新生产的list和之前的list没有关系
    test_list = ["a",1,"b","c",2,3,4]
    test_list2 = test_list.copy()
    
    print(test_list2)
    
    print(id(test_list),id(test_list2))
    # 43318472 43318280
    test_list.append("abc")
    print(test_list)
    # ['a', 1, 'b', 'c', 2, 3, 4, 'abc']
    print(test_list2)
    # ['a', 1, 'b', 'c', 2, 3, 4]
    




    # 4、count

    # 统计list中元素的个数
    print(test_list.count(2))
    # 1
    



    # 5、extend

    # 追加一个列表到另外一个列表的尾部
    test_list.extend(test_list2)
    print(test_list)
    # ['a', 1, 'b', 'c', 2, 3, 4, 'abc', 'a', 1, 'b', 'c', 2, 3, 4]
    




    # 6、index

    # 返回指定元素的索引,只返回第一个
    print(test_list.index(1))
    # 1
    




    # 7、insert

    # 在指定索引的位置插入元素
    test_list.insert(0,"xxxxxxxxx")
    print(test_list)
    # ['xxxxxxxxx', 'a', 1, 'b', 'c', 2, 3, 4, 'abc', 'a', 1, 'b', 'c', 2, 3, 4]
    




    # 8、pop

    # 删除指定元素的索引
    res = test_list.pop(0)
    
    print(res)
    # xxxxxxxxx
    print(test_list)
    # ['a', 1, 'b', 'c', 2, 3, 4, 'abc', 'a', 1, 'b', 'c', 2, 3, 4]
    





    # 9、remove

    # 移除遇到的第一个元素
    test_list.remove(2)
    print(test_list)
    



    # 10、reverse

    # 翻转列表
    test_list.reverse()
    print(test_list)
    # [4, 3, 2, 'c', 'b', 1, 'a', 'abc', 4, 3, 'c', 'b', 1, 'a']
    




    # 11、sort

    # 排序列表
    def test(i):
        if str(i).__contains__("a"):
            return 1
        else:
            return 2
    
    test_list.sort(key=test,reverse=True)
    
    print(test_list)
    # [4, 3, 2, 'c', 'b', 1, 4, 3, 'c', 'b', 1, 'a', 'abc', 'a']
    
  • 相关阅读:
    猴子分香蕉
    打鱼晒网
    质数/素数
    三角形-->九九乘法表
    eclipse 导入gradle引入多模块项目,引入eclipse后变成了好几个工程
    linux 命令基础大全
    SQL Server 增加链接服务器
    Postgresql数据库部署之:Postgresql 存在session 会话不能删除数据库
    Postgresql数据库部署之:Postgresql本机启动和Postgresql注册成windows 服务
    Git常用命令使用大全
  • 原文地址:https://www.cnblogs.com/bainianminguo/p/6403958.html
Copyright © 2020-2023  润新知