Python-1数据结构

本文深入探讨了数据结构的基本概念,包括列表、栈、队列的使用与操作,以及如何进行数据转换。同时,文章详细讲解了字典、集合等数据类型的特点与应用,并提供了丰富的代码实例。

数据结构

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值