- Python程序设计:编程基础、Web开发及数据分析
- 李辉 刘洋编著
- 889字
- 2025-02-15 22:57:39
4.6 容器的公共操作
容器是一种把多个元素组织在一起的数据结构,容器中的元素可以逐个地迭代获取,可以用in或not in关键字判断元素是否包含在容器中。
容器是一种可以包含其他类型对象(如列表、元组、字典等)作为元素的对象。容器仅仅只是用来存放数据的。
接下来针对容器中公共操作,结合示例讲解相关操作。
4.6.1 运算符操作
在上述序列中,常常都会用到+、*、in和not in,接下来对各个运算符进行解释。
1.“+”运算符
“+”运算符,主要用于字符串、列表、元组的合并操作。
【例4-56】“+”运算符的应用示例。

运行结果:

2.“*”运算符
“*”运算符,主要用于字符串、列表、元组的复制操作。
【例4-57】“*”运算符的应用示例。


运行结果:

3.“in”“not in”运算符
“in”“not in”运算符,主要用于判断字符串、列表、元组、字典的元素是否存在。
【例4-58】“in”“not in”运算符的应用示例。

运行结果:

4.6.2 公共方法
在序列方法中,常用的公共方法有len()方法、del或del()方法、max()和min()方法、range()方法和enumerate()方法。后面的两个方法已经在前边讲述过,所以此处不再论述。
1.len()方法
len()方法可以统计字符串、列表、元组、字典容器中的元素个数。
【例4-59】 len()方法应用示例。

运行结果:

2.del()方法
del()方法用于删除字符串、列表部分或全部元素。
【例4-60】 del()方法应用示例。

运行结果:

3.max()和min()方法
max()方法和min()方法分别返回容器中元素最大值和最小值。
【例4-61】 max()方法和min()方法的应用示例。
str1='abcdefg'list1=[10,20,30,40,50]#max():最大值print(max(str1))print(max(list1))#min():最小值print(min(str1))print(min(list1))
运行结果:
g 50 a 10
4.6.3 容器类型转换
在上述的各类容器中,可以通过tuple()、list()和set()三种方法进行相互转换。
1.tuple()方法
tuple()方法作用:将某个序列转换成元组。
【例4-62】 tuple()方法的应用示例。
list1=[10,20,30,40,50,20]s1={100,200,300,400,500}print(tuple(list1))print(tuple(s1))
运行结果:
(10,20,30,40,50,20)(100,200,300,400,500)
2.list()方法
list()方法作用:将某个序列转换成列表。
【例4-63】 list()方法的应用示例。
t1=('a','b','c','d','e')s1={100,200,300,400,500}print(list(t1))print(list(s1))
运行结果:
['a','b','c','d','e'][100,200,300,400,500]
3.set()方法
set()方法作用:将某个序列转换成集合。
【例4-64】 set()方法的应用示例。


运行结果:
