zoukankan      html  css  js  c++  java
  • Python基础: 列表的基本使用

    列表的定义:

    List(列表) 是 Python 中使用 最频繁 的数据类型,在其他语言中通常叫做 数组
    专门用于存储 一串 信息
    列表用 [] 定义,数据 之间使用  , 分隔
    列表的 索引 从 `0` 开始
    
    注意:从列表中取值时,如果 **超出索引范围**,程序会报错
    

    列表常用方法:

    In [1]: name_list.
    name_list.append   name_list.count    name_list.insert   name_list.reverse
    name_list.clear    name_list.extend   name_list.pop      name_list.sort
    name_list.copy     name_list.index    name_list.remove 
    

    方法演示:

    # 定义一个列表
    name_list = ["zhangsan", "wangwu", "lisi"]
    
    # 输出列表内容
    print(name_list[1])
    # 输出指定内容的索引
    print(name_list.index("lisi"))
    # 指定下标/索引输出 -- 下标是从 0 开始的
    name_list[1] = "张三"
    print(name_list[1])
    # 在列表末尾追加内容
    name_list.append("王小二")
    print(name_list)
    # 在指定位置插入内容
    name_list.insert(0, "小杰")
    print(name_list)
    # 将另一个列表扩展到另一个末尾
    temp_list = ["孙悟空","天蓬元帅"]
    name_list.extend(temp_list)
    print(name_list)
    # 弹出末尾的列表元素
    name_list.pop()
    print(name_list)
    # 移除指定元素
    name_list.remove("小杰")
    print(name_list)
    # 弹出指定元素
    name_list.pop(1)
    print(name_list)
    # 清空整个列表
    name_list.clear()
    print(name_list)
    
    
    name_list = ["zhangsan", "wangwu", "lisi"]
    
    temp_list = ["孙悟空","天蓬元帅"]
    name_list.extend(temp_list)
    print(name_list)
    # 反转列表
    name_list.reverse()
    print(name_list)
    # 将列表排序
    name_list.sort()
    print(name_list)
    
    # 将变量从内存中删除
    del name_list[1]
    print(name_list)
    # 复制列表内容
    copy_list = name_list.copy()
    print(copy_list)
    
    

    列表的数据统计:

    name_list = ["张三", "李四", "王五", "张三"]
    # 得到列表的长度
    name_len = len(name_list)
    print(name_len)
    # 列表中某个元素的个数
    zhangsan_cnt = name_list.count("张三")
    print(zhangsan_cnt)
    # 移除时会按照顺序移除
    name_list.remove("张三")
    print(name_list)
    
    
    

    列表排序及反转:

    name_list = ["张三", "李四", "王五", "张三"]
    name_num = [7, 8, 9, 1, 4]
    
    # 升序排序
    name_list.sort()
    name_num.sort()
    
    print(name_num)
    print(name_list)
    
    # 降序排序
    name_num.sort(reverse=True)
    name_list.sort(reverse=True)
    
    print(name_list)
    print(name_num)
    
    # 反转列表
    name_list.reverse()
    name_num.reverse()
    print(name_num)
    print(name_list)
    
    import keyword
    
    print(len(keyword.kwlist))
    

    列表遍历:

    name_list = ["张三", "李四", "王五", "张三"]
    
    name_list.insert(4,"张三")
    
    for name in name_list:
        print(name)
    
  • 相关阅读:
    【cocos2d-js官方文档】二、资源管理器Assets Manager
    【cocos2d-js官方文档】七、CCFileUtils
    【cocos2d-js官方文档】九、cc.loader
    【cocos2d-js官方文档】十二、对象缓冲池
    【cocos2d-js官方文档】十二、对象缓冲池
    【cocos2d-js官方文档】二十一、v3相对于v2版本的api变动
    【cocos2d-js教程】cocos2d-js 遮挡层(禁止触摸事件传递层)
    cocos2d-js中怎么删除一个精灵
    MS Chart 折线图——去除时间中的时、分、秒,按天统计【转】
    MS Chart 条状图【转】
  • 原文地址:https://www.cnblogs.com/prjruckyone/p/12757345.html
Copyright © 2011-2022 走看看