Python数据容器

本文详细介绍了Python中的基本数据容器,包括list、tuple、string、set和dict的操作,如查找、修改、插入、删除、遍历以及各种操作方法,如sort、index、count、append、extend、remove、clear等,展示了如何进行元素的增删改查和统计,以及各种容器之间的转换和比较。此外,还涵盖了序列和切片的概念,以及集合的差集、合并等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

list列表

list列表的查找操作

list列表的修改操作

list列表的插入和追加操作

list列表的删除操作

list列表的统计操作

list列表的循环遍历

tuple元组

 定义元组

元组的操作

元组的嵌套操作

字符串

序列和切片

集合

集合的添加和删除

集合的差集与合并

集合的遍历

字典

嵌套字典

字典的常用操作

字典的遍历

字典的课后练习

数据容器的通用功能

字符串大小比较

list列表

my_list = ["itheima", "itcast", "python"]
print(my_list)        #['itheima', 'itcast', 'python']
print(type(my_list))    #<class 'list'>

my_list = ["itheima", 666, True]
print(my_list)
print(type(my_list))

# 定义一个嵌套的列表
my_list = [ [1, 2, 3], [4, 5, 6]]
print(my_list)
print(type(my_list))    # <class 'list'>
print(my_list[0][0])
print(my_list[-1][-2])  # 5

# 通过下标索引取出对应位置的数据
my_list = ["Tom", "Lily", "Rose"]
# 列表[下标索引], 从前向后从0开始,每次+1,  从后向前从-1开始,每次-1
print(f"{my_list[0]}\t", end='')
print(my_list[1])
print(my_list[2])
# 错误示范;通过下标索引取数据,一定不要超出范围
# print(my_list[3])

# 通过下标索引取出数据(倒序取出)
print(my_list[-1])
print(my_list[-2])
print(my_list[-3])


# 取出嵌套列表的元素
my_list = [ [1, 2, 3], [4, 5, 6]]
print(my_list[1][1])

list列表的查找操作

mylist = ["itcast", "itheima", "python"]
# 1.1 查找某元素在列表内的下标索引
index = mylist.index("itheima")
print(f"itheima在列表中的下标索引值是:{index}")    #1
# 1.2如果被查找的元素不存在,会报错
# index = mylist.index("hello")
# print(f"hello在列表中的下标索引值是:{index}")

list列表的修改操作

mylist[0] = "传智教育"
print(f"列表被修改元素值后,结果是:{mylist}")

list列表的插入和追加操作

# 4. 在列表的尾部追加```单个```新元素
mylist.append("黑马程序员")
print(f"列表在追加了元素后,结果是:{mylist}")
# 5. 在列表的尾部追加```一批```新元素    将其他数据容器的内容取出,依次追加到列表尾部
mylist2 = [1, 2, 3]
mylist.extend(mylist2)
print(f"列表在追加了一个新的列表后,结果是:{mylist}")

list列表的删除操作

# 6. 删除指定下标索引的元素(2种方式)
mylist = ["itcast", "itheima", "python"]

# 6.1 方式1:del 列表[下标]
del mylist[2]
print(f"列表删除元素后结果是:{mylist}")

# 6.2 方式2:列表.pop(下标)
mylist = ["itcast", "itheima", "python"]
element = mylist.pop(2)
print(f"通过pop方法取出元素后列表内容:{mylist}, 取出的元素是:{element}")
# 7. 删除某元素在列表中的 第一个 匹配项
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
mylist.remove("itheima")
print(f"通过remove方法移除元素后,列表的结果是:{mylist}")

# 8. 清空列表
mylist.clear()
print(f"列表被清空了,结果是:{mylist}")

list列表的统计操作

# 9. 统计列表内某元素的数量
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
count = mylist.count("itheima")
print(f"列表中itheima的数量是:{count}")

# 10. 统计列表中全部的元素数量
mylist = ["itcast", "itheima", "itcast", "itheima", "python"]
count = len(mylist)
print(f"列表的元素数量总共有:{count}个")

list列表的循环遍历

def list_while_func():
    """
    使用while循环遍历列表的演示函数
    :return: None
    """
    mylist = ["传智教育", "黑马程序员", "Python"]
    # 循环控制变量:通过下标索引来控制,默认0
    index = 0
    while index < len(mylist):
        element = mylist[index]
        print(f"列表的元素:{element}")
        index += 1

list_while_func()


def list_for_func():
    """
    使用for循环遍历列表的演示函数
    for循环用于从容器内依次取出元素并处理
    :return:
    """
    my_list = [1,2,3,4,5]
    for element in my_list:
        print(f"列表的元素有:{element}")

list_for_func()

list = [1,2,3,4,5,6,7,8,9,10]
new_list = []

for i in list:
    j = 0
    if i % 2 == 0:
        new_list.append(i)
        j += 1
print(f"列表中的偶数为{new_list}")

列表的sort方法

1、准备列表

my_list = [["a", 33], ["b", 55], ["c", 11]]

 2、排序(基于带名函数)

def choose_sort_key(element):
    return element[1]     # 按照元素的哪一部分去排序

my_list.sort(key=choose_sort_key, reverse=True)    # [['b', 55], ['a', 33], ['c', 11]]

# 列表.sort(key=选择排序依据的函数, reverse=True)
#     参数key,要求传入一个函数,表示将列表的每一个元素都传入函数中,返回排序的依据
#         True表示降序

3、 排序(基于lambda匿名函数)

my_list.sort(key=lambda element: element[1], reverse=True)

print(my_list)

tuple元组

元组想要传递的信息,不可以被篡改;

一旦定义完成就不可以被修改

 定义元组

# 定义元组
t1 = (1, "Hello", True)
t2 = ()
t3 = tuple()
print(f"t1的类型是:{type(t1)}, 内容是:{t1}")   # t1的类型是:<class 'tuple'>, 内容是:(1, 'Hello', True)
print(f"t2的类型是:{type(t2)}, 内容是:{t2}")   # t2的类型是:<class 'tuple'>, 内容是:()
print(f"t3的类型是:{type(t3)}, 内容是:{t3}")   # t3的类型是:<class 'tuple'>, 内容是:()

# 定义单个元素的元素     必须在后面单独加一个逗号
t4 = ("hello", )
print(f"t4的类型是:{type(t4)}, t4的内容是:{t4}")
# 元组的嵌套
t5 = ((1, 2, 3), (4, 5, 6))
print(f"t5的类型是:{type(t5)}, 内容是:{t5}")

# 下标索引去取出内容
num = t5[1][2]
print(f"从嵌套元组中取出的数据是:{num}")    # 6
num1 = t5[1]
print(f"从嵌套元组中取出的数据是:{num1}")   # (4, 5, 6)

元组的操作

# 元组的操作:index查找方法
t6 = ("传智教育", "黑马程序员", "Python")
index = t6.index("黑马程序员")
print(f"在元组t6中查找黑马程序员,的下标是:{index}")    # 1

# 元组的操作:count统计方法
t7 = ("传智教育", "黑马程序员", "黑马程序员", "黑马程序员", "Python")
num = t7.count("黑马程序员")
print(f"在元组t7中统计黑马程序员的数量有:{num}个")      # 3个

# 元组的操作:len函数统计元组元素数量
t8 = ("传智教育", "黑马程序员", "黑马程序员", "黑马程序员", "Python")
num = len(t8)
print(f"t8元组中的元素有:{num}个")  # 5个

# 元组的遍历:while
index = 0
while index < len(t8):
    print(f"元组的元素有:{t8[index]}")
    # 至关重要
    index += 1

# 元组的遍历:for
for element in t8:
    print(f"2元组的元素有:{element}")

元组的嵌套操作

# 不可以修改元组内容,但是如果元组里面嵌套了列表元素,可以修改列表list里面的内容
# t8[0] = "itcast"

# 定义一个元组
t9 = (1, 2, ["itheima", "itcast"])
print(f"t9的内容是:{t9}")
t9[2][0] = "黑马程序员"
t9[2][1] = "传智教育"
print(f"t9的内容是:{t9}")

字符串

一个无法修改的数据容器

my_str = "itheima and itcast"
# 通过下标索引取值
value = my_str[2]
value2 = my_str[-16]
print(f"从字符串{my_str}取下标为2的元素,值是:{value},取下标为-16的元素,值是:{value2}")

# my_str[2] = "H"

# index方法
value = my_str.index("and")
print(f"在字符串{my_str}中查找and,其起始下标是:{value}")

# replace方法     将字符串中全部的字符串1,换为字符串2
new_my_str = my_str.replace("it", "程序")
print(f"将字符串{my_str},进行替换后得到:{new_my_str}")
# split方法   按照指定的分隔符字符串,将字符串划分为多个字符串,并存入列表对象中
my_str = "hello python itheima itcast"
my_str_list = my_str.split(" ")
print(f"将字符串{my_str}进行split切分后得到:{my_str_list}, 类型是:{type(my_str_list)}")

# strip方法   不传入参数,去除首尾空格
my_str = "  itheima and itcast  "
new_my_str = my_str.strip() # 不传入参数,去除首尾空格
print(f"字符串{my_str}被strip后,结果:{new_my_str}")    # itheima and itcast

my_str = "12itheima and itcast21"
new_my_str = my_str.strip("12")     # 划分为两个小子串,只要满足任何一个就去掉
print(f"字符串{my_str}被strip('12')后,结果:{new_my_str}")    # itheima and itcast
# 统计字符串中某字符串的出现次数, count
my_str = "itheima and itcast"
count = my_str.count("it")
print(f"字符串{my_str}中it出现的次数是:{count}")
# 统计字符串的长度, len()
num = len(my_str)
print(f"字符串{my_str}的长度是:{num}")

序列和切片

序列:内容连续、有序、可使用下标索引的一类数据容器

列表、元组、字符串均可以视为序列

# 对list进行切片,从1开始,4结束,步长1
my_list = [0, 1, 2, 3, 4, 5, 6]
result1 = my_list[1:4:1]      # 步长默认是1,所以可以省略不写
print(f"结果1:{result1}")     # [1, 2, 3]

# 对tuple进行切片,从头开始,到最后结束,步长1
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result2 = my_tuple[:]     # 起始和结束不写表示从头到尾,步长为1可以省略
print(f"结果2:{result2}")  # (0, 1, 2, 3, 4, 5, 6)

# 对str进行切片,从头开始,到最后结束,步长2   (跳过1个元素取)
my_str = "01234567"
result3 = my_str[::2]
print(f"结果3:{result3}")     # 0246

# 对str进行切片,从头开始,到最后结束,步长-1     (反向取)
my_str = "01234567"
result4 = my_str[::-1]          # 等同于将序列反转了
print(f"结果4:{result4}")     # 76543210

# 对列表进行切片,从3开始,到1结束,步长-1
my_list = [0, 1, 2, 3, 4, 5, 6]
result5 = my_list[3:1:-1]
print(f"结果5:{result5}")     # [3, 2]

# 对元组进行切片,从头开始,到尾结束,步长-2
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result6 = my_tuple[::-2]
print(f"结果6:{result6}")     # (6, 4, 2, 0)

集合

集合中不允许出现重复的内容,集合是无序的,所以不支持下标索引访问

集合和列表一样,允许修改

# 定义集合
my_set = {"传智教育", "黑马程序员", "itheima", "传智教育", "黑马程序员", "itheima", "传智教育", "黑马程序员", "itheima"}
my_set_empty = set()        # 定义空集合
print(f"my_set的内容是:{my_set}, 类型是:{type(my_set)}")   # my_set的内容是:{'黑马程序员', 'itheima', '传智教育'}, 类型是:<class 'set'>
print(f"my_set_empty的内容是:{my_set_empty}, 类型是:{type(my_set_empty)}")
# my_set_empty的内容是:set(), 类型是:<class 'set'>

集合的添加和删除

# 添加新元素
my_set.add("Python")
my_set.add("传智教育")      #
print(f"my_set添加元素后结果是:{my_set}")

# 移除元素
my_set.remove("黑马程序员")
print(f"my_set移除黑马程序员后,结果是:{my_set}")

# 随机取出一个元素
my_set = {"传智教育", "黑马程序员", "itheima"}
element = my_set.pop()
print(f"集合被取出元素是:{element}, 取出元素后:{my_set}")

# 清空集合, clear
my_set.clear()
print(f"集合被清空啦,结果是:{my_set}")

集合的差集与合并

# 取2个集合的差集
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.difference(set2)    # set1里面有而set2里面没有的
print(f"取出差集后的结果是:{set3}")      # 取出差集后的结果是:{2, 3}
print(f"取差集后,原有set1的内容:{set1}")
print(f"取差集后,原有set2的内容:{set2}")

# 消除2个集合的差集     消除两个集合中相同的内容
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set1.difference_update(set2)
print(f"消除差集后,集合1结果:{set1}")    # {2, 3}
print(f"消除差集后,集合2结果:{set2}")    # {1, 5, 6}

# 2个集合合并为1个
set1 = {1, 2, 3}
set2 = {1, 5, 6}
set3 = set1.union(set2)
print(f"2集合合并结果:{set3}")    # {1, 2, 3, 5, 6}
print(f"合并后集合1:{set1}")
print(f"合并后集合2:{set2}")      # {1, 5, 6}

集合的遍历

# 集合的遍历
# 集合不支持下标索引,不能用while循环
# 可以用for循环
set1 = {1, 2, 3, 4, 5, 5}
for element in set1:
    print(f"集合的元素有:{element}")

字典

字典中Key不允许重复,重复添加等同于覆盖原有数据

# 定义字典
my_dict1 = {"王力鸿": 99, "周杰轮": 88, "林俊节": 77}
# 定义空字典
my_dict2 = {}
my_dict3 = dict()
print(f"字典1的内容是:{my_dict1}, 类型:{type(my_dict1)}")   # <class 'dict'>
print(f"字典2的内容是:{my_dict2}, 类型:{type(my_dict2)}")   # 字典2的内容是:{}, 类型:<class 'dict'>
print(f"字典3的内容是:{my_dict3}, 类型:{type(my_dict3)}")   # 字典3的内容是:{}, 类型:<class 'dict'>

# 定义重复Key的字典
my_dict1 = {"王力鸿": 99, "王力鸿": 88, "林俊节": 77}
print(f"重复key的字典的内容是:{my_dict1}")   # {'王力鸿': 88, '林俊节': 77}

# 从字典中基于Key获取Value
my_dict1 = {"王力鸿": 99, "周杰轮": 88, "林俊节": 77}
score = my_dict1["王力鸿"]
print(f"王力鸿的考试分数是:{score}")
score = my_dict1["周杰轮"]
print(f"周杰轮的考试分数是:{score}")

嵌套字典

stu_score_dict = {
    "王力鸿": {
        "语文": 77,
        "数学": 66,
        "英语": 33
    }, "周杰轮": {
        "语文": 88,
        "数学": 86,
        "英语": 55
    }, "林俊节": {
        "语文": 99,
        "数学": 96,
        "英语": 66
    }
}
print(f"学生的考试信息是:{stu_score_dict}")

# 从嵌套字典中获取数据
# 看一下周杰轮的语文信息
score = stu_score_dict["周杰轮"]["语文"]
print(f"周杰轮的语文分数是:{score}")
score = stu_score_dict["林俊节"]["英语"]
print(f"林俊节的英语分数是:{score}")

字典的常用操作

my_dict = {"周杰轮": 99, "林俊节": 88, "张学油": 77}
# 新增元素
my_dict["张信哲"] = 66
print(f"字典经过新增元素后,结果:{my_dict}")

# 更新元素
my_dict["周杰轮"] = 33
print(f"字典经过更新后,结果:{my_dict}")

# 删除元素
score = my_dict.pop("周杰轮")
print(f"字典中被移除了一个元素,结果:{my_dict}, 周杰轮的考试分数是:{score}")

# 清空元素, clear
my_dict.clear()
print(f"字典被清空了,内容是:{my_dict}")

字典的遍历

# 获取全部的key
my_dict = {"周杰轮": 99, "林俊节": 88, "张学油": 77}
keys = my_dict.keys()
print(f"字典的全部keys是:{keys}")

# 遍历字典
# 方式1:通过获取到全部的key来完成遍历
for key in keys:
    print(f"字典的key是:{key}")
    print(f"字典的value是:{my_dict[key]}")

# 方式2:直接对字典进行for循环,每一次循环都是直接得到key
for key in my_dict:
    print(f"2字典的key是:{key}")
    print(f"2字典的value是:{my_dict[key]}")
# 不可以使用while循环

# 统计字典内的元素数量, len()函数
num = len(my_dict)
print(f"字典中的元素数量有:{num}个")      # 3个

字典的课后练习

# 组织字典记录数据
info_dict = {
    "王力鸿": {
        "部门": "科技部",
        "工资": 3000,
        "级别": 1
    },
    "周杰轮": {
        "部门": "市场部",
        "工资": 5000,
        "级别": 2
    },
    "林俊节": {
        "部门": "市场部",
        "工资": 7000,
        "级别": 3
    },
    "张学油": {
        "部门": "科技部",
        "工资": 4000,
        "级别": 1
    },
    "刘德滑": {
        "部门": "市场部",
        "工资": 6000,
        "级别": 2
    }
}

print(f"员工在升值加薪之前的结果:{info_dict}")

# for循环遍历字典
for name in info_dict:
    # if条件判断符合条件员工
    if info_dict[name]["级别"] == 1:
        # 升职加薪操作
        # 获取到员工的信息字典
        employee_info_dict = info_dict[name]
        # 修改员工的信息
        employee_info_dict["级别"] = 2    # 级别+1
        employee_info_dict["工资"] += 1000    # 工资+1000
        # 将员工的信息更新回info_dict
        info_dict[name] = employee_info_dict

# 输出结果
print(f"对员工进行升级加薪后的结果是:{info_dict}")

数据容器的通用功能

my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
my_str = "abcdefg"
my_set = {1, 2, 3, 4, 5}
my_dict = {"key1": 1, "key2": 2, "key3": 3, "key4": 4, "key5": 5}

# len元素个数
print(f"列表 元素个数有:{len(my_list)}")
print(f"元组 元素个数有:{len(my_tuple)}")
print(f"字符串元素个数有:{len(my_str)}")
print(f"集合 元素个数有:{len(my_set)}")
print(f"字典 元素个数有:{len(my_dict)}")

# max最大元素
print(f"列表 最大的元素是:{max(my_list)}")
print(f"元组 最大的元素是:{max(my_tuple)}")
print(f"字符串最大的元素是:{max(my_str)}")
print(f"集合 最大的元素是:{max(my_set)}")
print(f"字典 最大的元素是:{max(my_dict)}")
# min最小元素
print(f"列表 最小的元素是:{min(my_list)}")
print(f"元组 最小的元素是:{min(my_tuple)}")
print(f"字符串最小的元素是:{min(my_str)}")
print(f"集合 最小的元素是:{min(my_set)}")
print(f"字典 最小的元素是:{min(my_dict)}")
# 类型转换: 容器转列表
print(f"列表转列表的结果是:{list(my_list)}")
print(f"元组转列表的结果是:{list(my_tuple)}")
print(f"字符串转列表结果是:{list(my_str)}")
print(f"集合转列表的结果是:{list(my_set)}")
print(f"字典转列表的结果是:{list(my_dict)}")
# 类型转换: 容器转元组
print(f"列表转元组的结果是:{tuple(my_list)}")
print(f"元组转元组的结果是:{tuple(my_tuple)}")
print(f"字符串转元组结果是:{tuple(my_str)}")
print(f"集合转元组的结果是:{tuple(my_set)}")
print(f"字典转元组的结果是:{tuple(my_dict)}")
# 类型转换: 容器转字符串
print(f"列表转字符串的结果是:{str(my_list)}")     # “[1, 2, 3, 4, 5]”才是真正的结果
print(f"元组转字符串的结果是:{str(my_tuple)}")
print(f"字符串转字符串结果是:{str(my_str)}")
print(f"集合转字符串的结果是:{str(my_set)}")
print(f"字典转字符串的结果是:{str(my_dict)}")
# 类型转换: 容器转集合
print(f"列表转集合的结果是:{set(my_list)}")
print(f"元组转集合的结果是:{set(my_tuple)}")
print(f"字符串转集合结果是:{set(my_str)}")   #{'b', 'g', 'a', 'f', 'c', 'e', 'd'}数据会无序,同时还会去重
print(f"集合转集合的结果是:{set(my_set)}")
print(f"字典转集合的结果是:{set(my_dict)}")  #{'key3', 'key2', 'key1', 'key4', 'key5'}

# 进行容器的排序   然后放入列表当中
my_list = [3, 1, 2, 5, 4]
my_tuple = (3, 1, 2, 5, 4)
my_str = "bdcefga"
my_set = {3, 1, 2, 5, 4}
my_dict = {"key3": 1, "key1": 2, "key2": 3, "key5": 4, "key4": 5}

#排完序之后的结果都是列表对象
print(f"列表对象的排序结果:{sorted(my_list)}")    # [1, 2, 3, 4, 5]
print(f"元组对象的排序结果:{sorted(my_tuple)}")
print(f"字符串对象的排序结果:{sorted(my_str)}")
print(f"集合对象的排序结果:{sorted(my_set)}")
print(f"字典对象的排序结果:{sorted(my_dict)}")

print(f"列表对象的反向排序结果:{sorted(my_list, reverse=True)}")
print(f"元组对象的反向排序结果:{sorted(my_tuple, reverse=True)}")
print(f"字符串对象反向的排序结果:{sorted(my_str, reverse=True)}")
print(f"集合对象的反向排序结果:{sorted(my_set, reverse=True)}")
print(f"字典对象的反向排序结果:{sorted(my_dict, reverse=True)}")

字符串大小比较

# abc 比较 abd
print(f"abd大于abc,结果:{'abd' > 'abc'}")   # true
# a 比较 ab
print(f"ab大于a,结果:{'ab' > 'a'}")     # true
# a 比较 A    小写字母的ASCII码值比大写字母的ASCII码值大32
print(f"a 大于 A,结果:{'a' > 'A'}")     # true
# key1 比较 key2
print(f"key2 > key1,结果:{'key2' > 'key1'}")  # true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值