• python基础学习(七)列表


    列表的定义

    • List(列表) 是 Python 中使用 最频繁 的数据类型,在其他语言中通常叫做 数组(例如java、c)
    • 专门用于存储 一串 信息
    • 列表用 [] 定义,数据 之间使用 , 分隔
    • 列表的 索引0 开始
      • 索引 就是数据在 列表 中的位置编号,索引 又可以被称为 下标
      • 注意:从列表中取值时,如果 超出索引范围,程序会报错
    • 定义列表:name_list = ["zhangsan", "lisi", "wangwu"]

    列表的常见操作

        如何知道列表中提供了哪些方法呢?操作如下:

    • 打开ipython3,输入name_list. ,按下tab键会提示列表中所有的方法:
    • 列表的取值操作:list[index]、list.index(obj)
      # 1. 取值和取索引
      
      # 取值
      print(name_list[1])
      
      # 取索引
      print(name_list.index("lisi"))
    • 列表的添加操作的方法有:list.insert、list.append、list.extend
      # 2. 增加操作
      
      # 向列表末尾追加数据
      name_list.append("zhangfengxian")
      
      # 向指定索引插入数据
      name_list.insert(1, "zq")
      
      # 把其他列表的数据追加到末尾
      temp_list = ["Jake", "Rory", "Rose"]
      name_list.extend(temp_list)
    • 列表的修改操作:list[index] = xxxx
      # 3. 修改
      
      name_list[0] = "pipi"
    • 列表的删除操作:list.remove、list.pop、list.clear
      # 4. 删除
      
      # 删除指定的数据
      name_list.remove("wangwu")
      
      # 删除末尾的数据
      name_list.pop()
      
      # 删除指定位置的数据
      name_list.pop(1)
      
      # 清楚所有数据
      name_list.clear()

       del关键同样也可以删除列表中的数据,它还是删除某一个定义的变量:

      name_list = ["zhangsan", "lisi", "wangwu"]
      
      # del删除列表中的数据
      del name_list[1]
      
      name = "wangsan"
      
      # 删除name这个变量
      del name
      
      # 后续使用name这个变量会报错:NameError: name 'name' is not defined
      print(name)
      
      print(name_list)
    • 列表的统计:len,list.count
      # 5. 统计
      name_list = ["zhangsan", "lisi", "wangwu", "lisi"]
      
      # 列表的长度
      print("列表的长度为:%d" % len(name_list))
      
      # 数据在列表中出现的次数
      print("lisi出现的次数为:%d" % name_list.count("lisi"))
    • 列表排序:list.sort、list.reverse
      name_list = ["zhangsan", "lisi", "wangwu"]
      num_list = [11, 2, 5, 66, 12, 3]
      
      # 升序
      # name_list.sort()
      # num_list.sort()
      
      # 降序
      # name_list.sort(reverse=True)
      # num_list.sort(reverse=True)
      
      # 反转
      name_list.reverse()
      num_list.reverse()
      
      print(name_list)
      print(num_list)

    循环遍历

    • 遍历 就是 从头到尾 依次列表 中获取数据
      • 循环体内部 针对 每一个元素,执行相同的操作
    • Python 中为了提高列表的遍历效率,专门提供的 迭代 iteration 遍历
    • 使用 for 就能够实现迭代遍历
    • 流程图如下:
    • 遍历列表的简单例子如下:

      name_list = ["zhangsan", "lisi", "wangwu"]
      
      for name in name_list:
          print("My name is %s" % name)

    --本文完--

  • 相关阅读:
    html5画饼形图
    jqGrid添加详细按钮,单击弹出窗体
    Groovy的MOP和元编程学习笔记(超级牛逼的功能)
    使用PowerMockito和Mockito进行模拟测试,包括静态方法测试,私有方法测试等,以及方法执行的坑或者模拟不成功解决
    mysql 索引无法使用问题
    float/double 浮点数据*100精度丢失问题
    使用Groovy的sql模块操作mysql进行多种查询
    groovy与java中的多方法
    fastdfs+nginx集群高可用搭建的一些坑!!记录一下
    keepalived vrrp_script脚本不执行解决办法
  • 原文地址:https://www.cnblogs.com/zhangfengxian/p/python-list.html
Copyright © 2020-2023  润新知