04_数据结构
数据结构
列表(list)
列表内置的方法
方法 | 解释 |
---|---|
list.append(value) |
在列表的最后位置新增元素 |
list.extend(list) |
在列表最后位置新增一段列表 |
list.insert(value, index) |
在列表指定位置插入值 |
list.remove() |
从列表中删除第一个值为 x 的元素,未找到指定元素时,触发 ValueError 异常 |
list.pop(index) |
删除指定位置的元素,并返回该元素 |
list.index(value[, start, end]) |
返回列表中第一个值为 x 的元素的零基索引,未找到指定元素时,触发 ValueError 异常 |
list.count(value) |
返回出现元素value的次数 |
list.clear() |
清空整个列表 |
list.sort() |
按照升序就地排列此列表 |
list.reverse() |
翻转列表中的元素 |
list.copy() |
返回列表的浅拷贝。 类似于 a[:] |
>>> list = []
>>> list.append(1)
>>> list.append('2')
>>> list
[1, '2']
>>> new_list = [3, 4, '5']
>>> list.extend(new_list)
>>> list
[1, '2', 3, 4, '5']
>>> list.insert(len(list) - 2, 'insert value')
>>> list
[1, '2', 3, 'insert value', 4, '5']
>>> list.remove('3')
Traceback (most recent call last):
File "<python-input-9>", line 1, in <module>
list.remove('3')
~~~~~~~~~~~^^^^^
ValueError: list.remove(x): x not in list
>>> list.remove(3)
>>> list
[1, '2', 'insert value', 4, '5']
>>> list.pop(len(list))
Traceback (most recent call last):
File "<python-input-12>", line 1, in <module>
list.pop(len(list))
~~~~~~~~^^^^^^^^^^^
IndexError: pop index out of range
>>> list.pop(3)
4
>>> list
[1, '2', 'insert value', '5']
>>> len(list)
4
>>> list.clear
<built-in method clear of list object at 0x000001CA74752480>
>>> list.clear()
>>> list
[]
>>> for num in range(10):
... list.append(num)
...
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list.index(5,0,3)
Traceback (most recent call last):
File "<python-input-21>", line 1, in <module>
list.index(5,0,3)
~~~~~~~~~~^^^^^^^
ValueError: 5 is not in list
>>> list.index(5,0,6)
5
>>> list.index(5)
5
>>> list.extend([2,2,2])
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 2, 2]
>>> list.count(2)
4
>>> list.sort()
>>> list
[0, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list.reverse()
>>> list
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 2, 1, 0]
>>> list.copy()
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 2, 1, 0]
用列表实现堆栈
列表方法使得将列表用作栈非常容易,最后添加的元素会最先被取出(“后进先出”)。 要将一个条目添加到栈顶,可使用 append()
。 要从栈顶取出一个条目,则使用 pop()
且不必显式指定索引
stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
用列表实现队列
列表也可以用作队列,最先加入的元素,最先取出(“先进先出”);然而,列表作为队列的效率很低。因为,在列表末尾添加和删除元素非常快,但在列表开头插入或移除元素却很慢(因为所有其他元素都必须移动一位)
from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry 到了
>>> queue.append("Graham") # Graham 到了
>>> queue.popleft() # 第一个到的现在走了
'Eric'
>>> queue.popleft() # 第二个到的现在走了
'John'
>>> queue # 按到达顺序排列的剩余队列
deque(['Michael', 'Terry', 'Graham'])
del 关键字
不同于list.pop()
,del
不返回删除的参数,但是可以做到删除切片,或者删除整个变量
>>> list
[9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 2, 1, 0]
>>> del list[0]
>>> list
[8, 7, 6, 5, 4, 3, 2, 2, 2, 2, 1, 0]
>>> del list[2: 4]
>>> list
[8, 7, 4, 3, 2, 2, 2, 2, 1, 0]
>>> del list
>>> list
<class 'list'> #删除后 整个list变量就不存在了 不会像list.clear() 会返回一个空列表 []
元组(tuple)和序列(range)
元组由多个逗号隔开的值组成
t = 1, 2, 3, 4
print(t[0])
print(t)
new_t = t, 'hello', 'word'
print(new_t)
1
(1, 2, 3, 4)
((1, 2, 3, 4), 'hello', 'word')
元组是不可变对象
>>> t = 1, 2, 3, 4
>>> t[0] = 11
Traceback (most recent call last):
File "<python-input-46>", line 1, in <module>
t[0] = 11
~^^^
TypeError:
但是元组可以包含可变对象
v = ([1, 2, 3, 4], [5, 6, 7, 8])
print(v)
print(v[0].index(1))
print(len(v)) #元组的长度 2
v[1].append(2)
print(v)
([1, 2, 3, 4], [5, 6, 7, 8])
0
2
([1, 2, 3, 4], [5, 6, 7, 8, 2])
解包
new_tuple = 111, 222, 'hello_word'
x, y, z = new_tuple
print(new_tuple)
print(x, y, z)
(111, 222, 'hello_word')
111 222 hello_word
用变量与元组中的变量一一对应
序列解包 也是妥妥的,适用于右侧的任何序列。序列解包时,左侧变量与右侧序列元素的数量应相等。注意,多重赋值其实只是元组打包和序列解包的组合
new_list_tuple = [1, 2, 3], [4, 5, 6]
new_x, new_y = new_list_tuple
print(new_x, new_y)
[1, 2, 3] [4, 5, 6]
集合
集合是一个不含有重复元素的无序容器
两种方法创建集合
-
使用
{}
创建集合#使用花括号{}创建集合 nums = {1, 2, 4, 5, 6, 7, 8} print(3 in nums) print(5 in nums) False True
-
使用
set()
创建集合#使用set()创建集合 strs = set('aefbsefvbadfa') print(strs) {'v', 'e', 'f', 'd', 'b', 'a', 's'} #不含有重复元素的无序集合
字典
可以把字典理解为 键值对 的集合,但字典的键必须是唯一的
字典是以 键 来索引的,键可以是任何不可变类型;字符串和数字总是可以作为键
创建字典
-
使用
{}
创建字典dict_1 = {} print(dict_1) dict_2 = {'english': 'hello', 'chinese': '你好'} print(dict_2) {} {'english': 'hello', 'chinese': '你好'}
-
使用
dict()
对键值对序列创建字典list = [('num_1', 1), ('num_2', 2), ('num_3', 3)] print(list) new_dict = dict(list) print(new_dict) [('num_1', 1), ('num_2', 2), ('num_3', 3)] {'num_1': 1, 'num_2': 2, 'num_3': 3}
对字典进行增删改查
-
使用唯一键名能够直接在字典最后位置增加新的元素
dict_2['中文'] = '很高兴认识你' print(dict_2) {'english': 'hello', 'chinese': '你好', '中文': '很高兴认识你'}
-
dict_name['key_name'] = new_value
修改字典中的元素dict_2['chinese'] = '很高兴认识你' print(dict_2) {'english': 'hello', 'chinese': '很高兴认识你', '中文': '很高兴认识你'}
-
使用
in
查找目标键
是否存在于字典中print('chinese' in dict_2) True
-
使用
del
删除字典中的键值对del dict_2['chinese'] print(dict_2) {'english': 'hello', '中文': '很高兴认识你'}
-
#对字典使用list()则返回一个包含字典中所有键的列表
print(list(dict_2))
print(sorted(dict_2))
['chinese', 'english']
循环的技巧
-
对字典执行循环时, 可以使用
dict.item()
取出字典中的键值对new_dict_1 = {'gallahad': 'the pure', 'robin': 'the brave'} for i, j in new_dict_1.items(): print(i, 'and', j) gallahad and the pure robin and the brav
-
在序列中循环时,用
enumerate()
函数可以同时取出位置索引和对应的值:>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
-
同时循环两个或多个序列时,用
zip()
函数可以将其内的元素一一匹配:>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.
-
为了逆向对序列进行循环,可以求出欲循环的正向序列,然后调用
reversed()
函数:>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1
-
按指定顺序循环序列,可以用
sorted()
函数,在不改动原序列的基础上,返回一个重新的序列:>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for i in sorted(basket): ... print(i) ... apple apple banana orange orange pear
-
使用
set()
去除序列中的重复元素。使用sorted()
加set()
则按排序后的顺序,循环遍历序列中的唯一元素:>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear
-
一般来说,在循环中修改列表的内容时,创建新列表比较简单,且安全:
>>> import math >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] >>> filtered_data = [] >>> for value in raw_data: ... if not math.isnan(value): ... filtered_data.append(value) ... >>> filtered_data [56.2, 51.7, 55.3, 52.5, 47.8]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)