1.常用操作
列表常用操作
- 在 ipython 中定义一个 列表,例如: l= list()
-
输入 l. 按下 TAB 键, ipython 会提示 字典 能够使用的函数如下:
-
可以到官方网址查询使用方法:
insert、append需要达到熟练的程度,pop / sort 用的也比较多就地操作(修改原来的内容), 拷贝一份进行操作(不会修改原来的值,但是会返回一个新的内容)
案例:
其他用方法
- 使用in判断值是否存在
- 使用 += 合并列表
- 使用 len() 获取长度
- 使用join()转换为字符串

2.元组与列表的区别
- 元组一旦定义就不允许更改。
- 元组没有 append() 、 extend() 和 insert() 等方法,无法向元组中添加元素。
- 元组没有 remove() 或 pop() 方法,也无法对元组元素进行 del 操作,不能从元组中删除元素。
- 从效果上看, tuple( ) 冻结列表,而 list( ) 融化元组。
元组的优点
- 元组的速度比列表更快。如果定义了一系列常量值,而所需做的仅是对它进行遍历,那么一般使用元组而不用列表。
- 元组对不需要改变的数据进行 “写保护” 将使得代码 更加安全 。
- 元组可用作字典的“键”,也可以作为集合的元素。列表永远不能当做字典键使用,也不能作为集合的元素,因为列表不是不可变的。
- 不可变
3.dict(字典)
定义:字典是一种可变的、无序的、键值对的、复杂的数据容器
Python 中的字典是Python中一个键值映射的数据结构。
字典是一种可变无序数据容器,且可存储任意类型对象。字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中
字典的定义
字典用 {} 定义
字典使用 键值对 存储数据,键值对之间使用 , 分隔
- 键 key 是索引
- 值 value 是数据
- 键 和 值 之间使用 : 分隔
- 键必须是唯一的
- 值 可以取任何数据类型,但 键 只能使用 字符串、数字或 元组

字典常用操作
使用 字典['键'] 可以取到字典里面的内容。

使用 字典['键'] = 值 修改字典内容。

当键不存在时添加内容。

字典常用方法

有关 字典 的 常用操作 可以参照上图练习

循环遍历
- 遍历 就是 依次 从 字典 中获取所有键值对

提示:在实际开发中,由于字典中每一个键值对保存数据的类型是不同的,所以针对字典的循环遍历需求并不是很多
案例:对Python之禅的单词计数
统计python之禅中每个字符出现的次数

拓展:对字典进行排序输出


4.set(集合)
与数学中的集合功能一样
集合(set)是一种无序的、可变的、不可重复的数据类型。
集合用 {} 创建,一般用作于去重

集合运算(了解)
可以进行数学中的集合运算

@拓展
列表推导式
推导式comprehensions(又称解析式),是Python的一种独有特性。推导式是可以从一个数据序列构建另一个新的数据序列的结构体。


序列解包
解包在英文里叫做 Unpacking,就是将容器里面的元素释放出来。Python 中的解包是自动完成的,例如:

_ 是被舍弃的变量