第五讲:Python的数据集合
目录:
一、容器技术
容器:
Python程序运行过程中可以包含其他对象的对象,叫做容器.
Python中常用的容器有四类:
- 列表(
List
). - 元组(
Tuple
). - 字典(
Dict
). set
集合(Set
).
1.1 列表
列表介绍:
- 用中括号来包裹.
- 所有元素都是有顺序的.
索引:
- 从
0
开始,由左向右排序.
0 1 2 3 4 ...
.
反向索引:- 从
-1
开始,由右向左排序.
-5 -4 -3 -2 -1 ...
.
列表基本操作:
创建列表:
lst = ['abc', 12, [10, 20]]
nums = [10, 20, 30, 40, 50, 60]
my_emt = [] # 空列表,没有任何元素.
列表中的任意一个元素都不限定数据类型.
查询列表:
# 使用下标来查找单个元素.
nums = [10, 20, 30, 40, 50, 60]
print(nums[3])
# 切片技术:使用下标来查找多个元素.
# 注意:索引序列包头不包尾.
# 正向索引:
print(nums[2:6]) # [30, 40, 50, 60]
# 反向索引:
print(nums[-4:]) # [30, 40, 50, 60]
print(nums[:-2]) # [10, 20, 30, 40]
- 返回单个元素所对应的下标
nums = [10, 20, 30, 40, 50, 60]
print(nums.index(50))
- 返回列表的长度
nums = [10, 20, 30, 40, 50, 60]
print(len(nums))
- 判断某一个元素是否存在
nums = [10, 20, 30, 40, 50, 60]
if 30 in nums:
print('存在列表中!')
else:
print('不存在列表中!')
- 循环遍历
nums = [10, 20, 30, 40, 50, 60]
for i in nums:
print(i)
新增操作:
append函数
:
nums = [10, 20, 30, 40, 50, 60]
nums.append(70)
print(nums)
insert函数
:
# 把80添加到下标为0的位置.
nums = [10, 20, 30, 40, 50, 60]
nums.insert(0, 80)
print(nums)
append
只能把新增的元素添加到列表的最后位置.
删除操作:
pop函数
:
nums &