赞
踩
目录
列表是一种有序、可变的数据容器。它可以存储任意类型的数据,包括数字、字符串、列表等。列表使用方括号 [] 来定义,各个元素之间用逗号分隔。
- # 定义一个列表 list
- my_list = ['zhanyijia', 'hello', 'python']
- print(my_list)
- print(type(my_list))
-
- my_list = ['zhanyojai', 12345, True]
- print(my_list)
- print(type(my_list))
- # 定义一个嵌套的列表
- my_list = [['hello', 1, 2], [3, 4, 5]]
- print(my_list)
- print(type(my_list))
-
- my_list.append(1)
- print(my_list)
'运行
运行结果:
列表的下标索引从0开始,逐个递增。例如,对于一个长度为n的列表,第一个元素的下标索引为0,最后一个元素的下标索引为n-1。可以使用下标索引来获取列表中的特定元素,也可以使用负数的下标索引来从列表末尾开始访问元素,例如-1表示最后一个元素,-2表示倒数第二个元素。
- # 通过下标索引取出对应位置的数据
- my_list = ['tom',"lily","rose"]
- print(my_list[0])
- print(my_list[1])
- print(my_list[2])
- print(my_list[-1])
- print(my_list[-2])
- print(my_list[-3])
'运行
运行结果:
list.index("元素"):查找元素所在的索引下标,查找不到会报错
list.insert(插入位置,"元素"):在指定下标位置插入元素
list.append("元素"):将元素追加到列表最后
list.extend(list1):将list1追加到list中
list.clear():清空列表
list.count("元素"):计算元素在list中的个数
删除元素:del 列表[下标], 列表.pop(下标), 列表.remove("元素")
- my_list = ["hello", "ityijia", "python"]
- # 查找某元素再列表内的下标索引
- index= my_list.index("hello") # 查询不到会报错
- print(index)
-
- # 修改特定位置的元素值
- my_list[0] = '你好'
- print(f"列表被修改元素值后,结果是:{my_list}")
-
- # 在指定下标位置插入元素
- my_list.insert(1, "bbbbbb")
- print(f"列表被插入元素值后,结果是:{my_list}")
-
- # 追加元素
- my_list.append("520")
- print(f"列表被追加元素值后,结果是:{my_list}")
- # 追加一批元素
- list2 = [1, 2, 3]
- my_list.extend(list2)
- print(f"列表被追加一批元素值后,结果是:{my_list}")
-
- # 删除元素,删除指定索引元素
- del my_list[2] # 方法一,del 列表[下标]
- my_list.pop(1) # 方法二,列表.pop(下标)
- my_list.remove('python') # 方法三 列表.remove(元素)
-
- # 清空列表
- my_list.clear()
- print(f"列表被清空的结果是:{my_list}")
-
- # 统计某元素在列表内的数量
- list3 = [1, 1, 1, 1, 2, 2, 2, 4, 4, 5, 543]
- count = list3.count(1)
- print(f"列表中1的数量是:{count}")
-
- # 统计列表全部元素数量
- num = len(list3)
- print(num)
'运行
运行结果:
- def list_while_func():
- """
- 使用while循环遍历列表的演示函数
- :return:
- """
- my_list = ["你好","你真好","python"]
- # 循环条件,下标索引变量<列表的元素数量
- index = 0
- while index < len(my_list):
- element = my_list[index]
- print(f"列表的元素:{element}")
- index += 1
-
-
- def list_for_func():
- """
- 使用for循环遍历列表的演示函数
- :return:
- """
- my_list = [1,2,3,4,5,6]
- for element in my_list:
- print(f"列表的元素有:{element}")
-
-
- list_while_func()
- list_for_func()
-
- # 练习案例,定义一个列表,内容是:[1,2,3,4,5,6,7,8,9,10]
- # 遍历列表,取出偶数存入一个新的列表中,使用while循环和for循环各操作一次
- list = [1,2,3,4,5,6,7,8,9,10]
- index1 = 0
- list_1 = []
- list_2 = []
- while index1 < len(list):
- element = list[index1]
- if element % 2 == 0:
- list_1.append(element)
- index1 += 1
-
- for element in list:
- if element % 2 == 0:
- list_2.append(element)
-
- print(list_1)
- print(list_2)
'运行
运行结果:
元组是一种有序、不可变的数据容器。它可以存储任意类型的数据,和列表类似,但元组的元素不可修改。元组使用圆括号 () 来定义,各个元素之间用逗号分隔。
- # 定义元组
- t1 = (1, "hello", True)
- t2 = ()
- t3 = tuple()
- # 定义单个元素的元组
- t4 = ("hello", )
-
- # 元组的嵌套
- t5 = ((1, 2, 3), (4, 5, 6))
-
- # 下标索引取出内容
- num = t5[1][2]
- print(num)
'运行
str.index("元素"):查找元素的起始下标
str.replace("原字符串", "新字符串"):将原的字符串替换为新的字符串。
str.split():字符串的分割,字符串本身不变,会得到一个新的列表对象
str.strip():去除前后空格。
str.strip("字符串"):去除前后指定字符串
- my_str = "my name is zhanyijia"
-
- # index方法
- value = my_str.index("name")
- print(f"字符串{my_str}中查找name,其起始下标是:{value}")
-
- # replace方法,字符串的替换
- my_str_replace = my_str.replace("name", "isisisis")
- print(my_str_replace) #是一个新的字符串
-
- # split方法,字符串分割,字符串本身不变,会得到一个列表对象
- list = my_str.split(" ")
- print(list)
-
- # strip方法
- # 字符串.strip(),去除前后空格
- # 字符串.strip(字符串),去除前后指定字符串
- my_str = " my name is iiiiii "
- new_my_str = my_str.strip()
- print(new_my_str)
- newnew_my_str = new_my_str.strip("my")
- print(newnew_my_str)
'运行
运行结果:
- # 对list进行切片,从1开始,4结束,步长1
- list = [0,1,2,3,4,5,6,7]
- result1 = list[1:4]
- print(f"结果1:{result1}")
-
- # 对tuple进行切片,从头开始,最后结束,步长1
- tuple1 = (0,1,2,3,4,5,6,7)
- result2 = tuple1[:]
- print(f"结果2:{result2}")
-
- # 对str进行切片,从头开始,最后结束,步长2
- str = "01234568789"
- result3 = str[::2]
- print(f"结果3:{result3}")
-
- # 对str进行切片,从头开始,最后结束,步长-1
- my_str = "0123456789"
- result4 = my_str[::-1]
- print(f"结果4:{result4}")
-
- # 对列表进行切片,从3开始,到1结束,步长-1
- my_list = [0,1,2,3,4,5,6,7]
- result5 = my_list[3:1:-1]
- print(f"结果5:{result5}")
-
- # 对元组进行切片,从头开始,最后结束,步长-2
- my_tuple1 = (0,1,2,3,4,5,6,7)
- result6 = my_tuple1[::-2]
- print(f"结果6:{result6}")
'运行
运行结果:
- # 将字符串中:“万过薪月,居悦亦区湾来,nohtyp学”
- # 用学过方法,得到“湾区亦悦居”
- # 方法一:可切片取出,然后倒序
- # 方法二:split分隔“,” replace替换“来”为空,倒序字符串
-
- # 方法一
- str = "万过薪月,居悦亦区湾来,nohtyp学"
- result1 = str[9:4:-1]
- print(result1)
-
- # 方法二
- split = str.split(",") # 分隔逗号,中文逗号
- print(split[1][4::-1])
'运行
无序的可变容器,存储唯一的元素。集合使用花括号 {} 来表示,元素之间使用逗号分隔。
集合.add("元素"):添加新元素
集合.remove("元素"):移除元素
集合.pop():随机取出一个元素,同时元素会被删除
集合.clear():清空集合
集合1.difference(集合2):取出集合1和集合2的差集(集合1有而集合2没有的),会得到一个新集合
集合1.difference_update(集合2):在集合1内删除与集合2相同的集合,集合1被修改,集合2不变
集合1.union(集合2):将集合1与集合2合并为一个新集合
- # 定义集合,集合不允许元素重复,会去重,内容无序
- my_set = {"nihao", "hello word", "或许是", "nihao", "hello word", "或许是", "nihao", "hello word", "或许是"}
- my_set_empty = set() # 定义空集合
- print(f"my_set的内容是:{my_set},类型是{type(my_set)}")
- print(f"my_set_empty的内容是:{my_set_empty},类型是{type(my_set_empty)}")
-
- # 添加新元素
- my_set.add("python")
- print(f"my_set添加元素后的结果是:{my_set}")
-
- # 移除元素
- my_set.remove("nihao")
- print(f"my_set移除元素后的结果是:{my_set}")
-
- # 随机取出一个元素,同时元素会被删除
- my_set_pop = my_set.pop()
- print(my_set_pop)
-
- # 清空集合
- my_set.clear()
- print(my_set)
-
- # 取2个集合的差集
- # 集合1.difference(集合2),取出集合1和集合2的差集(集合1有而集合2没有的)
- # 会得到一个新集合
- set1 = {1, 2, 3}
- set2 = {1, 5, 6}
- set3 = set1.difference(set2)
- print(f"取出差集后的结果:{set3}")
- print(f"取出差集后,原有set1的结果:{set1}")
- print(f"取出差集后,原有set2的结果:{set2}")
-
- # 消除2个集合的差集
- # 集合1.difference_update(集合2)
- # 在集合1内,删除与集合2相同的元素,集合1被修改,集合2不变
- set1 = {1, 2, 3}
- set2 = {1, 5, 6}
- set1.difference_update(set2)
- print(f"消除差集后,集合1结果:{set1}")
-
- # 2个集合合并为1个,会得到一个新集合
- set1 = {1, 2, 3}
- set2 = {1, 5, 6}
- set3 = set1.union(set2)
- print(f"合并之后的结果是:{set3}")
- # 统计集合元素数量
- set1 = {1, 2, 3, 4, 5, 6, 7, 8}
- num = len(set1)
- print(f"集合内的元素数量有:{num}个")
-
- # 集合的遍历
- # 集合不支持下标索引,不能用while循环
- # 可以用for循环
- set1 = {1, 2, 3, 4, 5, 6}
- for element in set1:
- print(f"集合的元素有:{element}")
'运行
运行结果:
无序的可变容器,存储键-值对数据。字典使用花括号 {} 来表示,键-值对之间使用冒号 : 分隔,键-值对之间使用逗号分隔。
字典的相关用法:
- # 字典的定义
- my_dict1 = {"王力红": 99, "周杰轮": 88, "林俊节": 77}
- # 定义空字典
- my_dict2 = {}
- my_dict3 = dict()
-
- # 定义重复key的字典
- my_dict1 = {"王力红": 99, "王力红": 88, "林俊节": 77}
- print(f"重复key的字典内容是:{my_dict1}")
-
- # 从字典中基于key获取value
- my_dict1 = {"王力红": 99, "周杰轮": 88, "林俊节": 77}
- score = my_dict1["王力红"]
- print(f"王力红的考试分数为:{score}")
-
- # 定义嵌套字典
- stu_score_dict = {
- "王力红":{
- "语文":77,
- "数学":66,
- "英语":33
- },"周杰轮":{
- "语文": 88,
- "数学": 86,
- "英语": 99
- },"林俊节":{
- "语文": 23,
- "数学": 56,
- "英语": 44
- }
- }
-
-
- # 从嵌套字典中获取数据
- # 看一下周杰轮的语文信息
- score = stu_score_dict["周杰轮"]["语文"]
- print(f"周杰轮的语文分数:{score}")
-
- # 字典添加元素,如元素存在则更新字典
- my_dict1["猪猪"] = 789
- print(f"添加元素后的字典结果为:{my_dict1}")
-
- # 删除元素
- my_dict1.pop("林俊节")
- print(f"删除元素后的结果为:{my_dict1}")
-
- # 清空字典
- my_dict1.clear()
- print(f"清空字典后的结果为:{my_dict1}")
-
- # 获取全部的key
- my_dict4 = {"王力红": 99, "zhan": 88, "林俊节": 77}
- keys = my_dict4.keys()
- print(f"字典的全部key是:{keys}")
- # 拿到keys可以遍历字典,拿到全部的value值
- for k in keys:
- print(k)
'运行
运行结果:
sorted()方法:
- # 进行容器排序,排序之后会变成列表对象
- my_list = [5,2,1,4,8]
- my_tuple = (3,1,2,5,4)
- mt_str = "zxcvbnm"
- mt_set = {3,1,2,5,4}
- my_dict = {"key3":1,"key1":2,"key2":3,"key5":4,"key4":5,"key6":1}
-
- print(f"列表对象的排序结果:{sorted(my_list)}")
- print(f"元组对象的排序结果:{sorted(my_tuple)}")
- print(f"字符串对象的排序结果:{sorted(mt_str)}")
- print(f"集合对象的排序结果:{sorted(mt_set)}")
- print(f"字典对象的排序结果:{sorted(my_dict)}")
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。