python中的容器

时间:2025-04-09 07:49:54

目录

目录

1.容器的概念

2.列表(list(线性表))

1.定义列表的方法

1..根据python是弱数据类型语言特点

()

2.如何访问列表中的元素

3.如何遍历容器

4.创建方法

3.集合(set)---- 哈希结构(集合基于哈希结构实现的)

1.创建方法

2.集合特点

3.常见方法

4.元组(tuple)

1.创建元组的方法

2.特点

3.常见方法

4.注意

5.面试题

5.字典(dict)

1.创建方法

2.如何访问字典中的值

3.常见的方法:

4.如何遍历字典

6.字符串

1.什么是字符串

2.定义方法

3.常见的方法

7.排序

1.选择排序

2.冒泡排序

3.插入排序

8.切片操作

1.使用

2.注意


1.容器的概念

容器是一个可以存放多个元素的一种数据类型,弥补了变量只能存储一个元素的缺陷
其中包括   列表   元组   集合   字典

2.列表(list(线性表))

线性表(常见线性表数组 栈 队列 链表(单向链表和双向链表))是属于一种数据结构python中列表是基于链表(双向链表)实现

1.定义列表的方法

1..根据python是弱数据类型语言特点

ls = [1,2,3,4,5]

()

ls = list()

ls = list([1,2,3,4,5])

2.如何访问列表中的元素

通过下标访问元素,注意的是下标从 0 开始,如果下标超过范围会报错,可以通过下标改变元素值(修 改元素),下标也可以为负数
>>> ls = [1,2,3,4,5]
>>> ls [1, 2, 3, 4, 5] 
>>> ls[2] 
3
>>> ls[5] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range 
>>> ls[2] 
3
>>> ls[2] = 6 
>>> ls [1, 2, 6, 4, 5] 
>>> ls[-1] 
5
>>> ls[-5] 
1
>>> ls[-6] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range

3.如何遍历容器

#for 循环
for i in ls: 
    print(i) 
#while 循环 
index = 0 while index < len(ls): 
    print(ls[index]) 
    index += 1

4.创建方法

[ 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
object ------ 向列表尾部追加元素(添加)
>>> ls 
[1, 2, 6, 4, 5] 
>>> (7) 
>>> ls 
[1, 2, 6, 4, 5, 7]

2.insert(index,object) ------- 向指定位置(index)添加元素

>>> ls 
[1, 2, 6, 4, 5, 7] 
>>> (3,8) 
>>> ls 
[1, 2, 6, 8, 4, 5, 7]

3.sort() ---- 列表进行排序(默认从小到大的顺序 int,其他类型也可以进行排序(按照ASCII的值),注意排序的时候列表里元素的类型必须一致(单一)

>>> ls 
[1, 2, 6, 8, 4, 5, 7] 
>>> () 
>>> ls 
[1, 2, 4, 5, 6, 7, 8]
>>> ls1 
[]
>>> ls1 = ["A","a","D","C","e"] 
>>> () 
>>> ls1 
['A', 'C', 'D', 'a', 'e']

4.index() -------- 查找元素的位置,返回的是下标,如果元素有重复的情况下,返回的是元素第一次出现的位置,如果元素不存在会报错

>>> ls 
[1, 2, 4, 5, 6, 7, 8]
>>> (6) 
4
>>> (1) 
>>> ls 
[1, 2, 4, 5, 6, 7, 8, 1] 
>>> (1) 
0
>>> (9) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: 9 is not in list

5.reverse() ------- 将列表进行翻转

>>> ls 
[1, 2, 4, 5, 6, 7, 8, 1]
>>> () 
>>> ls 
[1, 8, 7, 6, 5, 4, 2, 1]

6.remove() ------- 通过元素移除列表中的元素,如果元素不存在会抛出异常(报错)

>>> ls 
[1, 8, 7, 6, 5, 4, 2, 1] 
>>> (2) 
>>> ls 
[1, 8, 7, 6, 5, 4, 1] 
>>> (9) Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: (x): x not in list

7.count() ------- 统计元素在列表中出现的次数(个数)

>>> (1) 
2
>>> ls 
[1, 8, 7, 6, 5, 4, 1] >>> 
(5) 
1

8.clear() ------- 清除元素(注意:慎用)

>>> ls 
[1, 8, 7, 6, 5, 4, 1] 
>>> () 
>>> ls 
[]

9.copy() ------ 拷贝列表(浅拷贝 拷贝不等价与= 在堆内存中进行对象的拷贝)

>>> ls = [1,2,3,4,5] 
>>> ls1 
['A', 'C', 'D', 'a', 'e'] 
>>> () 
[1, 2, 3, 4, 5] 
>>> ls1 = () 
>>> ls1 
[1, 2, 3, 4, 5] 
>>> ls 
[1, 2, 3, 4, 5]

10.extend() ------ 合并列表

>>> (ls1) 
>>> ls 
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5] 
>>> ls1 
[1, 2, 3, 4, 5] 
>>> ls2 
[1, 2, 3, 4, 5, 6] 
>>> (ls2) 
>>> ls1 
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]

11.pop() ----- 与append()相反,从列表尾部删除元素,有返回值,返回值是删除掉的这个元素,如果要删除指定位置的元素pop(index)

>>> ls 
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5] 
>>> () 
5
>>> ls 
[1, 2, 3, 4, 5, 1, 2, 3, 4] 
>>> (2) 
3

12.补充

a. 通过下标可以修改某个元素的值

b. 列表中的元素类型可以不同

c. 列表中的元素也可以是列表
[1, 2, 3, [1, 2, 3], 4, 5] 
>>> type(ls4) 
<class 'list'> 
>>> ls4[3][2] 
3

3.集合(set---- 哈希结构(集合基于哈希结构实现的)

1.创建方法

1. s = {1,2,3,4}
2. s = set()

2.集合特点

无序的,不能重复的(无序并不是指顺序 hash 底层 )
s[0] ------ 报错

3.常见方法

['add','clear','copy','difference','difference_update','discard','intersection','intersection_update',
'isdisjoint','issubset','issuperset','pop','remove','symmetric_difference',
'symmetric_difference_update', 'union', 'update']

1.add() ---- 添加元素,如果添加的元素是重复的情况下,不会报错,并且不会被二次添加

2.difference() ------ 差集

>>> s1 = {3,4,5,6,7,8} 
>>> s1 
{3, 4, 5, 6, 7, 8} 
>>> s 
{1, 2, 3, 4, 5} 
>>> (s1) 
{1, 2} 
>>> (s) 
{8, 6, 7}

3.intersection() ------ 交集

() ----- 并集

() ----- 更新集合,合并集合

>>> s 
{1, 2, 3, 4, 5} 
>>> s1 
{3, 4, 5, 6, 7, 8} 
>>> (s1) 
>>> s 
{1, 2, 3, 4, 5, 6, 7, 8}

6.discard() ---- 移除元素 ,如果元素不存在不做任何操作

4.元组(tuple)

1.创建元组的方法

1. t = (1,2,3,4)

2. t = tuple()

2.特点

1.有序的、元组是一个不可变类型(元组的元素一旦确定下来是不可变的) -------- 能用元组的情况尽 量不要用列表,因为元组相对于安全
2.可以通过下标去获取元素,但是不能去修改元素

3.常见方法

['count', 'index']

4.注意

元组是不可变的(指向不可变),但是元组中的元素可以是可变

>>> tt = (1,2,3,[1,2,3]) 
>>> type(tt) 
<class 'tuple'> 
>>> tt[3][1] = 4 
>>> tt 
(1, 2, 3, [1, 4, 3])

5.面试题

t = (1) t 类型是什么?
答:int类型
如何定义一个元素的元组
t = (1,)

5.字典(dict

1.创建方法

1. d = {"name":"zhangsan","age":18}

 2. d = dict()

2.如何访问字典中的值

通过key去访问value d["name"],如果没有这个value抛出异常

通过key修改value的值

通过key添加键值对(新key =新值 )

>>> d["name"]
'zhangsan'
>>> d["age"] = 20
>>> d
{'name': 'zhangsan', 'age': 20}
>>> d["gender"] = "男"
>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男'}

3.常见的方法:

['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
get(key) ----- 通过Key 获取 value, 如果没有 key 的话不会做任何操作,其实返回的 None
keys()---- 返回所有的键 (key)
values() ----- 返回所有的值 value
items() ----- 返回所有的键值对
>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男'}
>>> ()
dict_keys(['name', 'age', 'gender'])
>>> ()
dict_items([('name', 'zhangsan'), ('age', 20), ('gender', '男')])
>>> ()
dict_values(['zhangsan', 20, '男'])
setdefault() ----- 设置默认值
>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男'}
>>> ("name")
'zhangsan'
>>> ("password")
>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男', 'password': None}
>>> ("password")
pop(key) ---- 通过 key 去移除键值对,如果没有这个 key 会抛出异常
>>> d
{'name': 'zhangsan', 'age': 20, 'gender': '男', 'password': None}
>>> ("gender")
'男'
>>> d
{'name': 'zhangsan', 'age': 20, 'password': None}
>>> ("gender")
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
KeyError: 'gender'
popitem() ----- 移除键值对,根据后进先出的顺序进行删除
>>> help()
Help on built-in function popitem:

popitem() method of  instance
    Remove and return a (key, value) pair as a 2-tuple.

    Pairs are returned in LIFO (last-in, first-out) order.
    Raises KeyError if the dict is empty.

>>> d
{'name': 'zhangsan', 'age': 20, 'password': None}
>>> ()
('password', None)

4.如何遍历字典

>>> d
{'name': 'zhangsan', 'age': 20}
>>> for k in d:
...     print(k,(k))
...
name zhangsan
age 20
>>> for k in ():
...     print(k,d[k])
...
name zhangsan
age 20
>>> for k,v in ():
...     print(k,v)
...
name zhangsan
age 20

6.字符串

1.什么是字符串

由很多有效字符组成串

2.定义方法

双引号 单引号 三双引号 三单引号
s = str()

3.常见的方法

[ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
'partition', 'removeprefix', 'removesuffix', 'replace', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
capitalize() ---- 格式化字符串的方法 将字符串的首字母转换为大写
center(width, fillchar=' ') ---- 这是字符串长度居中
count() ---- 统计字符或者字符串出现的次数
>>> s
'hahahaha'
>>> ()
'Hahahaha'
>>> help()
Help on built-in function center:

center(width, fillchar=' ', /) method of  instance
    Return a centered string of length width.

    Padding is done using the specified fill character (default is a space).
>>> (30)
' hahahaha '
>>> (30,"*")
'***********hahahaha***********'
>>> s
'hahahaha'
>>> ("h")
4
>>> ("ha")
4
>>> ("haha")
2
endswith() ---- 判断字符串是不是以 XXX 结尾
startswith() ---- 判断字符串是不是以 XXX 开头
index() ---- 查询字符或者字符串在字符串中出现的第一次的位置,如果没有则抛出异常
rindex() ---- 从右往左找
find() -------- 查询字符或者字符串在字符串中出现的第一次的位置,如果没有则会返回 -1
rfind() ------ 从右往左找
encode() ---- 将字符串转换为字节数据的方法 如果要将字节数据转换为字符数据 decode() (这个方法是字节里面的方法 )
>>> ()
b'hahahaha'
>>> d = ()
>>> d
b'hahahaha'
>>> type(d)
<class 'bytes'>
>>> ()
'hahahaha'
>>> ss = ()
>>> type(ss)
<class 'str'>
format() ----- 格式化字符串 a = 3 b =2 print("a = {} ,b ={}".format(a,b))
islower() ------ 判断字母是否全为小写
isupper()------ 判断字母是否全为大写
istitle() ---- 判断是否为标题
isspace() --- 判断是否为空格位(了解)
isdigit() ---- 判断是否为数字
isalnum() ----- 不是判断是否位数字,判断是否为有效字符(数字、字母、下划线)
isalpha() ---- 是否全为字母
title() ----- 将字符串转换为标题
lower() ----- 将字符全部转换为小写
upper()------- 将字符全部转换为大写
split() ---- 将字符串按照特定的格式进行分割,返回值是一个列表
join() --- 按照特定的符号将一个可迭代对象拼接字符串(注意的是这个方法不是列表或者其他容的方法)
strip() ----- 清除字符串两侧空格
lstrip() ------- 清除字符串左侧空格
rstrip() ------- 清除字符串右侧空格
replace(old,new) ----- 用新的字符替换旧的字符
ljust() ------- 左对齐
rjust()------ 右对齐
>>> s
'hahahaha'
>>> ()
True
>>> ()
False
>>> ss = "This is ..."
>>> ()
False
>>> ss = "This Is .."
>>> ()
True
>>> s
'hahahaha'
>>> ()
False
>>> ss = "1234"
>>> ()
True
>>> ss = "$$$$$"
>>> ()
False
>>> s
'hahahaha'
>>> ()
True
>>> ()
True
>>> ss = "this is a dog"
>>> ()
'This Is A Dog'
>>> s
'hahahaha'
>>> ()
'HAHAHAHA'
>>> ss
'this is a dog'
>>> (" ")
['this', 'is', 'a', 'dog']
>>> ss
'this is a dog'
>>> ("s")
['thi', ' i', ' a dog']
>>> help()
Help on built-in function join:

join(iterable, /) method of  instance
    Concatenate any number of strings.

    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.

    Example: '.'.join(['ab', 'pq', 'rs']) -> ''

>>> ls = ["a","b","c"]
>>> " ".join(ls)
'a b c'
>>> "*".join(ls)
'a*b*c'
>>> ss = " name "
>>> ()
'name'
>>> s
'hahahaha'
>>> ("h","H")
'HaHaHaHa'
>>> s
'hahahaha'
>>> (30)
'hahahaha '
>>> (30)
' hahahaha'
>>> (30,"*")
'**********************hahahaha'

7.排序

1.选择排序

找最小值

arr = [8,3,2,6,1,4,9,7]
for i in range(0,len(arr)): # 0, 8
    for j in range(i+1,len(arr)):
        if arr[i] >= arr[j]:
            arr[i],arr[j] = arr[j],arr[i]
print(arr)

2.冒泡排序

找最大值

arr = [8,3,2,6,1,4,9,7]
for i in range(0,len(arr)-1): # 0, 7
    for j in range(0,len(arr)-1-i):
        if arr[j] >= arr[j+1]:
            arr[j],arr[j+1] = arr[j+1],arr[j]
print(arr)

3.插入排序

arr = [8,3,2,6,1,4,9,7]
for i in range(0,len(arr)):
    for j in range(i,0,-1):
        if arr[j] <= arr[j-1]:
            arr[j],arr[j-1] = arr[j-1],arr[j]
print(arr)

4.计数排序(桶排序)

# arr = [8,3,2,6,1,4,9,7]
arr = [7,3,2,0,1,2,3,6]
max_num = arr[0]
min_num = arr[0]
for num in arr:
    if num > max_num:
        max_num = num
    elif num < min_num:
        min_num = num
#print(max_num,min_num)
#偏移量
offest = min_num
#计算新列表的长度
len_arr1 = max_num - min_num + 1
#计数列表 ---- 初始化元素全为0
arr1 = [0] * len_arr1
# print(arr1)
#排序后的列表
arr2 = [0] * len_arr1
#计数
for num in arr:
    #print(num)
    arr1[num - offest] += 1
print(arr1)
index = 0
for i in range(0,len_arr1):
    for j in range(0,arr1[i]):
    print(i+offest,end="")
    arr2[index] = i + offest
    index += 1
print()
print(arr2)

8.切片操作

python 中是用来切割可迭代对象(容器)
一个完成的切片是包含两个:三个参数的
object[start:end:step]
range 函数相似(参数个数和取值范围)
step: 步长,默认取值是 1 ,可以为负数,默认方向是从左往右,负数代表从右往左
object[start:] :从start切割到结束位置(为最末端)包含最末端,方向是从左往右

object[start:end] :从start切割到end结束,不包含end(前闭后开),方向是从左往右

object[start:end:step]: 以step为单位从start切割到end结束不包含end(前闭后开),step为正数的时候方向是从左往右,step为负数的时候方向是从右往左

1.使用

a = [0,1,2,3,4,5,6,7,8,9]

//1. 切割获取单个值
>>> a[0]
0
>>> a[-4]
6

//2. 切割完整对象
>>> a[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::-1]#-1 从右往左
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

//3. start和end全部为正数的情况下
>>> a[1:6]
[1, 2, 3, 4, 5]
>>> a[1:6:-1] # start = 1 end = 6 表示从左往右 step=-1 表示的是从右往左 所以自相矛盾 返
回的是空
[]
>>> a[:6]
[0, 1, 2, 3, 4, 5]
>>> a[6:]
[6, 7, 8, 9]
>>> a[6::-1]
[6, 5, 4, 3, 2, 1, 0]

//4. start和end全部为负数的情况下
>>> a[-1:-6]
[]
>>> a[-1:-6:-1]
[9, 8, 7, 6, 5]
>>> a[:-6]
[0, 1, 2, 3]
>>> a[-6:-1]
[4, 5, 6, 7, 8]
>>> a[-6:]
[4, 5, 6, 7, 8, 9]
>>> a[-6::-1]
[4, 3, 2, 1, 0]

//5. start和end分别为正数和负数的情况下
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[1:-6]
[1, 2, 3]
>>> a[-1:-6]
[]
>>> a[1:-6:-1]
[]
>>> a[-1:6]
[]
>>> a[-1:6:-1]
[9, 8, 7]

//6. 连续切片操作
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:8][2:5][-1:]
[4]
a[:8]---- [0 1 2 3 4 5 6 7]---[2:5] ---[2,3,4]--[-1:]---[4]

//7. 其他对象的切片操作
>>> t = (1,2,3,4)
>>> t[1:3]
(2, 3)
>>> s = "ABCDEFG"
>>> s[1:3]
'BC'
>>> for i in range(1,100)[2::3][-10:]:
... print(i)
...
72
75
78
81
8487
90
93
96
99

//8. 切片的三个参数是表达式
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[2+1:3*2:7%3] #a[3:6:1]
[3, 4, 5]

2.注意

1. 如果进行切片操作的时候,超越下标的话不会报错
2. 如果进行切片操作的时候,参数的取值相互矛盾的话不会报错,会返回一个空列表
3. python 中实现反向列表输出的方法
        
        循环 () 切片 [::-1]