python3 0基础学习----数据结构(基础+练习)

python 0基础学习笔记之数据结构

  • [📚 几种常见数据结构](#📚 几种常见数据结构)
  • [📚 常用的内置函数](#📚 常用的内置函数)
    • [1. print(): 将制定的值输出到控制台](#1. print(): 将制定的值输出到控制台)
    • [2. len(sequence): 返回序列的长度(元素个数)](#2. len(sequence): 返回序列的长度(元素个数))
    • [3. type(object): 返回对象的类型](#3. type(object): 返回对象的类型)
    • [4. input('请输入') : 获取用户输入数据](#4. input('请输入') : 获取用户输入数据)
    • [5. range(初值, 终值, 步长)内置函数,返回的是一个可迭代对象。用于创建数字序列](#5. range(初值, 终值, 步长)内置函数,返回的是一个可迭代对象。用于创建数字序列)
    • [6. int(x)、float(x)、str(x)、bool(x) 等:将输入值转换为整数、浮点数、字符串或布尔值类型。](#6. int(x)、float(x)、str(x)、bool(x) 等:将输入值转换为整数、浮点数、字符串或布尔值类型。)
    • [7. max(iterable)、min(iterable):返回可迭代对象中的最大值和最小值。](#7. max(iterable)、min(iterable):返回可迭代对象中的最大值和最小值。)
    • [8. sum() 返回可迭代对象的和(用于数组类型的对象)](#8. sum() 返回可迭代对象的和(用于数组类型的对象))
    • [9. abs(x):返回数值的绝对值。](#9. abs(x):返回数值的绝对值。)
    • [10. round(number, ndigits):将数值四舍五入到指定的小数位数](#10. round(number, ndigits):将数值四舍五入到指定的小数位数)
    • [11. dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表](#11. dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表)
  • [📚 结合实战练习](#📚 结合实战练习)
    • [1. 列表中in和not in 的使用](#1. 列表中in和not in 的使用)
    • [练习2 :读取a.txt文件,对每一行使用split()方法拆分为单词列表,对每一行单词进行筛选去重复,添加到新的列表中。最后使用sort()进行排序。(大概意思是提取a.txt中出现过的单词生成一个列表)](#练习2 :读取a.txt文件,对每一行使用split()方法拆分为单词列表,对每一行单词进行筛选去重复,添加到新的列表中。最后使用sort()进行排序。(大概意思是提取a.txt中出现过的单词生成一个列表))
      • [1. a.txt文件内容(请忽略内容是什么意思,网上是那个随便找的)](#1. a.txt文件内容(请忽略内容是什么意思,网上是那个随便找的))
      • [2. 提取单词思路](#2. 提取单词思路)
      • [3. 代码:](#3. 代码:)
      • [4. 输出结果](#4. 输出结果)
    • [练习2 :读取一份邮件,获取到邮件中出现过的单词生成字典,并记录每个地址出现过的个数](#练习2 :读取一份邮件,获取到邮件中出现过的单词生成字典,并记录每个地址出现过的个数)
      • [1. a.txt内容和上一题一样](#1. a.txt内容和上一题一样)
      • [2. 思路](#2. 思路)
      • [3. 代码](#3. 代码)
      • [4. 运行结果](#4. 运行结果)
    • [练习3 :在练习2中升级,输出练习2中,单词出现最多的建和键值](#练习3 :在练习2中升级,输出练习2中,单词出现最多的建和键值)

📚 几种常见数据结构

列表 (List)

1. 定义

列表是一种有序的可变序列,可以包含不同类型的元素。列表可以通过方括号 [] 来表示,元素之间用逗号分隔

注释: 注意列表可变,字符串不可变,只能改变大小写

2. 实例:

python 复制代码
my_list = [1, 'hello', 3.14, True]

3. 列表中常用方法

.append(要添加内容) 向列表末尾添加数据

.extend(列表) 将可迭代对象逐个添加到列表中

.insert(索引,插入内容) 向指定位置插入内容

.remove(删除内容) 删除指定内容

.pop(索引) 删除指定索引处内容并返回删除内容

.index(要查询内容) 返回一个与制定元素匹配的索引,不改变原列表

.count(要查询内容) 返回列表中该元素出现次数

.sort() 同类型排序(默认升序),不同类型会报错TypeError: '<' not supported between instances of 'int' and 'str'

.reverse() 反向排序,不分类型

元组(Tuple)

1. 定义

元组是一种有序的不可变序列,同样可以包含不同类型的元素。元组可以通过圆括号 () 来表示,元素之间用逗号分隔

2. 实例:

python 复制代码
my_tuple = (1, 'hello', 3.14, True)

元组输出的是列表的子集

3. 元组中常用方法

因为元组是不可修改的所以只能查询,如果要修改得先转换成列表进行修改,之后在转换成元组

python 复制代码
x = (1,5,'i','j')
# x.sort() #报错 AttributeError: 'tuple' object has no attribute 'sort'
print(x[1]) #输出: 5
x[1] = 6 #报错 TypeError: 'tuple' object does not support item assignment

.index(element) 返回第一个与制定元素相等的元素的索引

.count(要查询内容) 返回列表中该元素出现次数

修改元组内容

字典(Dictionary)

1. 定义

字典是一种键值对的集合,键和值可以是任意的数据类型。字典可以通过花括号 {} 来表示,每个键值对使用冒号 : 分隔,键值对之间用逗号分隔。可做内容修改

python 复制代码
a={age:10}
a['age']=18
print(a) #输出 {'age': 18}

字典里边没有顺序 ,列表有从0开始

字典是直接删除重新加入,所以没有顺序

2. 实例:

python 复制代码
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

3. 字典中常用方法

in和not in方法

python 复制代码
a={'age':10,'name':'xiaoming'}
print('name' in a)  #输出 True
print('s' not in a)  #输出 True

for 键 in 字典

可以通过dict(健)=键值

for in 和items()结合使用

for 健,键值 in 字典.items()

python 复制代码
a = {'age':10,'name':'xiaoming'}
for (k,v) in a.items():  #()可加可不加
    print(k,v)

print(k,v) 输出:

python 复制代码
age 10
name xiaoming

.keys() 返回一个包含字典所有的视图

.values() 返回一个包含字典所有的视图

get(key, default):返回指定键的值,如果键不存在,则返回默认值(default)。

.pop(key):移除指定键的键值对,并返回键对应的值。

.popitem():随机移除并返回一个键值对

.update(): 使用其他字典内容更新当前字典

.clear():移除字典中的所有键值对。

.items() : 用于以键-值对(key-value pairs)

python 复制代码
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
items = my_dict.items()
print(items)

输出: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

集合(Set)

1. 定义

集合是一种无序的不重复的元素的集合。集合可以通过花括号 {} 或 set() 函数来创建

2. 实例:

python 复制代码
my_set = {1, 2, 3, 4, 5}

3. 集合常用方法

.add(element)向集合随机添加元素(因为无序所以随机)

.remove(element)从集合中删除某元素,如果该集合没有该元素返回错误KeyError



.discard(element)从集合中删除某元素,如果该集合没有该元素也不会报错

.pop()随机移初一个元素,并返回该元素(集合是无序的,无法确定删除的元素是那个)

.clear() 清除集合中所有元素,输出set()

.copy():复制一个集合

字符串(String)

1. 定义

字符串是一种由字符组成的不可变序列,可以用单引号或双引号括起来

2. 实例:

python 复制代码
my_string = 'Hello, World!'

3. 集合常用方法

上篇文章有写,跳转地址python3 0基础学习----基本知识

📚 常用的内置函数

1. print(): 将制定的值输出到控制台

python 复制代码
print('hi~') #输出 hi~

2. len(sequence): 返回序列的长度(元素个数)

3. type(object): 返回对象的类型

4. input('请输入') : 获取用户输入数据

5. range(初值, 终值, 步长)内置函数,返回的是一个可迭代对象。用于创建数字序列

python 复制代码
for num in range(5):
    print(num)  # 输出: 0, 1, 2, 3, 4

for num in range(2, 7):
    print(num)  # 输出: 2, 3, 4, 5, 6

for num in range(1, 10, 2):
    print(num)  # 输出: 1, 3, 5, 7, 9

6. int(x)、float(x)、str(x)、bool(x) 等:将输入值转换为整数、浮点数、字符串或布尔值类型。

python 复制代码
num1 = int("10")
num2 = float("3.14")
text = str(42)
flag = bool(1)

7. max(iterable)、min(iterable):返回可迭代对象中的最大值和最小值。

python 复制代码
my_list = [3, 1, 5, 2, 4]
max_value = max(my_list)
min_value = min(my_list)
print(max_value) #输出 5
print(min_value) #输出 1 

8. sum() 返回可迭代对象的和(用于数组类型的对象)

9. abs(x):返回数值的绝对值。

python 复制代码
s = abs(-10)
print(s) #输出 10

10. round(number, ndigits):将数值四舍五入到指定的小数位数

python 复制代码
rounded_num = round(3.14159, 2)
print(rounded_num) #输出3.14

11. dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表

python 复制代码
>>>dir()   #  获得当前模块的属性列表
['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
>>> dir([ ])    # 查看列表的方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>

📚 结合实战练习

1. 列表中in和not in 的使用

python 复制代码
some = [1,2,3,4,5,6]
print(3 in some) #输出 True
print(3 not in some) #输出 False

练习2 :读取a.txt文件,对每一行使用split()方法拆分为单词列表,对每一行单词进行筛选去重复,添加到新的列表中。最后使用sort()进行排序。(大概意思是提取a.txt中出现过的单词生成一个列表)

1. a.txt文件内容(请忽略内容是什么意思,网上是那个随便找的)

Dear Sir/Madam,

I am writing this email to express my gratitude to you and to discuss

some matters. I hope this email finds you in good health and high

spirits.

Firstly, I would like to sincerely thank you for your generosity and

assistance. I have been facing some difficulties in pursuing my career

goals, and your support has been invaluable to me. Your advice and

guidance have helped me gain a better understanding of the challenges

I have faced and have motivated me to continue striving.

The purpose of this email is to request a meeting with you in order to

personally express my gratitude. I would like the opportunity to

showcase the progress I have made in my professional development and

to hear your valuable insights. If you are willing, I can arrange the

meeting according to your convenience, and the location and date can

be adjusted according to your preferences.

Furthermore, I wanted to inquire if there is anything else I can do

for you. Your generosity may have an impact not only on me personally

but also on other individuals I may be able to assist. Please let me

know if there is anything you need help with, as I would be more than

happy to offer my assistance.

Once again, thank you for your support and generosity, and I hold

great expectations for the future. I sincerely look forward to meeting

with you and expressing my gratitude in person. If you have any

questions or require further information regarding the meeting, please

feel free to contact me.

With heartfelt appreciation,

[Your Name]

2. 提取单词思路

遍历文件每行内容

拆分每行内容为单词列表

遍历当前行列表单词

查找list中是否存在当前单词,存在记录出现个数,不存在新增一条记录

3. 代码:

python 复制代码
th = open('a.txt')
print('读取文件内容',th)
lst = list()#空列表
for item in th:
    itemStr = item.rstrip()# 去除末尾空白符号
    pList = itemStr.split()# 以空格作为分隔符分割每行数据,返回一个单词列表  ,例如首行:['Dear', 'Sir/Madam,']
    for word in pList:
         if len(lst)==0:
            lst.append(word)
            continue
         if len(lst)>0:
            if lst.count(word)>0:
                continue
            else:
                lst.append(word)


print('列表长度',len(lst))
lst.sort()
print(lst)

4. 输出结果

练习2 :读取一份邮件,获取到邮件中出现过的单词生成字典,并记录每个地址出现过的个数

1. a.txt内容和上一题一样

2. 思路

读取文件

声明空字典

遍历文件内容

去掉每行结尾空白符号

切割每行生成单词字典

3. 代码

python 复制代码
th = open('a.txt')
dictStr = dict()#空字典
for item in th:
    itemStr = item.rstrip()# 去除末尾空白符号
    pDict = itemStr.split()# 以空格作为分隔符分割每行数据,返回一个单词列表  ,例如首行:['Dear', 'Sir/Madam,']
    for word in pDict:
         dictStr[word] = dictStr.get(word,0)+1 #查找。找到获取对应值+1,没找到默认为0+1
# print(dictStr.items())#items方法,返回可迭代对象的(key,value)
print(sorted([(k,v) for k,v in dictStr.items()]))

4. 运行结果

练习3 :在练习2中升级,输出练习2中,单词出现最多的建和键值

python 复制代码
bigKey = None #最大键
bigValue = None  #最大键值
for k,v in dictStr.items():
    if bigKey is None or v>bigValue: # is判断是否相等,or或
        bigValue = v
        bigKey = k
print(bigKey,':',bigValue)

输出结果:to : 17

相关推荐
leegong231112 小时前
学习PostgreSQL专家认证
数据库·学习·postgresql
Moonnnn.3 小时前
51单片机学习——动态数码管显示
笔记·嵌入式硬件·学习·51单片机
夏末秋也凉3 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生3 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
王老师青少年编程3 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
技术小齐3 小时前
网络运维学习笔记 016网工初级(HCIA-Datacom与CCNA-EI)PPP点对点协议和PPPoE以太网上的点对点协议(此处只讲华为)
运维·网络·学习
竹言笙熙4 小时前
代码审计初探
学习·web安全
日记成书4 小时前
物联网智能项目
物联网·学习
虾球xz4 小时前
游戏引擎学习第118天
学习·游戏引擎
gz927cool4 小时前
大模型做导师之开源项目学习(lightRAG)
学习·开源·mfc