06-python_数据类型-列表

来源:互联网 发布:飞尸国语完整版网络 编辑:程序博客网 时间:2024/04/27 17:52

1. 引入

 1.1 概念
 - List 是 处理一组有序项目的数据结构
 - 列表 是 可变类型的数据, 即可给指定项目赋新值
 - 组成: 用"[]"界定, 其项目(/元素) 用逗号 分隔.
 - 举例: List1 = [1, 2, 3]
 
 1.2 创建
  
  1.2.1 使用[]
    >>> myList = [1,2,3]
    >>> myList
    [1, 2, 3]

  1.2.2 zip()
    >>> zip([1,2], ['a','b'])
    [(1, 'a'), (2, 'b')]

  1.2.3 range([start,] end [,step])
    >>> range(1, 10)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]

2. 操作

 - 取值
    - 切片 和 索引
    - list[index]
 - 添加
    - list.append(new) 末尾追加
    - list[1:1] = [...], 在index=1 处插入
 - 删除
    - del(list[index])
    - list.remove( list[index] | value)
 - 修改
    - list[index] = newValue
 - 查找
    - item in list

 2.1 取值
    >>> numList = [0, 1, 2, 3]
    >>> numList[1]
    1

 2.2 添加
  2.2.1 追加
    >>> numList = [0, 1, 2, 3]
    >>> numList.append(4)
    >>> numList
    [0, 1, 2, 3, 4]  

  2.2.2 插入
    >>> numList = [0, 1, 2]
    >>> numList[1:1] = ['a', 'b']
    >>> numList
    [0, 'a', 'b', 1, 2]
    >>> len(numList)
    5

 2.3 删除
  2.3.1 remove
    >>> strList = ['a', 'b', 'c']
    >>> strList.remove('b')
    >>> strList
    ['a', 'c']
    >>> strList.remove(strList[1])
    >>> strList
    ['a']

  2.3.2 del
    >>> numList = [0, 1, 2, 3]
    >>> del(1)
      File "<stdin>", line 1
    SyntaxError: can't delete literal
    >>> del(numList[1])
    >>> numList
    [0, 2, 3]

 2.4 查找
    >>> list = ['a', 'b']
    >>> list
    ['a', 'b']
    >>> 'a' in list
    True
    >>> 'a' not in list
    False

原创粉丝点击