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

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

📚 几种常见数据结构

列表 (List)

1. 定义

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

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

2. 实例:

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. 实例:

my_tuple = (1, 'hello', 3.14, True)

元组输出的是列表的子集

在这里插入图片描述

3. 元组中常用方法

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

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. 定义

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

a={age:10}
a['age']=18
print(a) #输出 {'age': 18}

字典里边没有顺序 ,列表有从0开始
字典是直接删除重新加入,所以没有顺序

2. 实例:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

3. 字典中常用方法

in和not in方法
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()

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

print(k,v) 输出:

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

.items() : 用于以键-值对(key-value pairs)
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. 实例:

my_set = {1, 2, 3, 4, 5}

3. 集合常用方法

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

在这里插入图片描述

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

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

.copy():复制一个集合

在这里插入图片描述

字符串(String)

1. 定义

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

2. 实例:

my_string = 'Hello, World!'

3. 集合常用方法

上篇文章有写,跳转地址python3 0基础学习----基本知识
在这里插入图片描述

📚 常用的内置函数

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

print('hi~') #输出 hi~

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

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

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

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) 等:将输入值转换为整数、浮点数、字符串或布尔值类型。

num1 = int("10")
num2 = float("3.14")
text = str(42)
flag = bool(1)

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

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):返回数值的绝对值。

s = abs(-10)
print(s) #输出 10

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

rounded_num = round(3.14159, 2)
print(rounded_num) #输出3.14

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

>>>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 的使用

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. 代码:

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. 代码

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中,单词出现最多的建和键值

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大白菜1号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值