数据结构
list 列表
1.基本操作
添加 (在末尾)
l = []
l.append(12)
l.append([12, 'iprice'])
l.extend([2])
插入(需知道插入位置)
l.insert(0, ‘uid’)
删除
del l[0] # 按索引
del l[2:4]
a = l.pop(0) # 弹出并删除
l.remove(12) # 按内容移除
while 12 in l: # 删除所有
l.remove(12)
l.clear() # 清空
求索引
x = l.index(‘ugender’)
求元素个数
i = l.count(‘uage’)
置换
l.reverse()
l = [1,2,3]
l.reverse() # 不能用于赋值 l2 = l.reverse()
print(l)
>> [3, 2, 1]
一个问题
n_list2 = num_list
num_list.reverse() # 结果显示, num_list置换后,n_list2也同样置换
if n_list2 == num_list:
return True
正确写法:
n_list2 = num_list.copy()
num_list.reverse() # 结果显示, num_list置换后,n_list2也同样置换
if n_list2 == num_list:
return True
复制
b = l.copy()
2.栈与队列
栈
l_stack = [3, 4, 5]
l_stack.append(6)
l_stack.append(7)
a = l_stack.pop()
print(a)
a = l_stack.pop()
print(l_stack)
队列
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
queue.popleft() # The first to arrive now leaves
queue.popleft() # The second to arrive now leaves
print(queue)
3. 转换
l = ['uage', 'ugender', 'ucountry','uage'] # list
s = set(l) # list--> set
l2i = {l:i for i, l in enumerate(s)} # set-->dict
print(l)
print(s)
print(l2i)
dict 字典
键-值 map-value
初始化
dict = {}
增
dict.setdefault(‘old’, 2) # {‘old’ : 2, }
改
dict[‘old’] = 20
删
dict.pop(‘old’)
查
‘old’ in dict # True or False
dict = {}
l = [1, 2]
print(dict)
for i in l:
dict.setdefault(i, 2) # 2不填则默认为None
print(dict)
set 集合
元素不重复
初始化
s = {1, 2, 3}
s = set([1, 2, 3]) # list->set
增
s. add(5)
删
s.remove(3)
查
4 in s # True or False
本文深入探讨了数据结构的基本概念,包括列表、栈、队列的使用与操作,以及如何进行数据转换。同时,文章详细讲解了字典、集合等数据类型的特点与应用,并提供了丰富的代码实例。

被折叠的 条评论
为什么被折叠?



