Python中的数据结构---栈,队列

介绍list的基本用法,栈和队列在list中的模拟

# 数据结构 list
items = []
print(type(items))
<class 'list'>
items = [1,2,4]
print(items[2])
4
# 索引 = 列表.index(元素)
letters = ['a','b','c']
letters.index('c')
2
letters = ['a','b','c']
print('a' in letters)
True
numbers = [1,2,1,1,1,1,1,4,5,6]
print(numbers.count(1))
6
# 向列表的末尾添加元素
letters = ['a','b']
tmp = letters.append('c')
print(tmp) #返回None
print(letters)
None
['a', 'b', 'c']
# 向列表任意位置添加元素 列表.insert(索引,元素)
letters = ['a','b']
letters.insert(0,'a')
print(letters)
['a', 'a', 'b']
#  在一个列表中添加另一个列表的所有元素,
# 直接在原来的列表中操作
# 返回值None
letters = ['a','b','c']
letters.extend(['d','e','f'])
print(letters)
['a', 'b', 'c', 'd', 'e', 'f']
#  删除对应索引元素
letters = ['a','c']
tmp = letters.pop(1)
print(tmp)
print(letters)
c
['a']
# 直接删除元素,返回值为None
letters = ['a','b','c']
tmp = letters.remove('a') #None
print(tmp)
print(letters)
None
['b', 'c']
# 反转整个列表
letters = ['a','b','c']
letters.reverse()
print(letters)

['c', 'b', 'a']
numbers = [2,3,6,7,3]
numbers.sort(reverse=True)
print(numbers)
numbers.sort() #排序
print(numbers)
[7, 6, 3, 3, 2]
[2, 3, 3, 6, 7]
# 栈的操作
# pop()
# append()
stack = ['a','b','c']
tmp = stack.pop()
print(tmp,stack)
stack.append('ddddd')
print(stack)
c ['a', 'b']
['a', 'b', 'ddddd']
#  队列的操作
#  pop()
# insert(0,element)
que = ['a','b']
que.insert(0,'aaaa')
print(que)
tmp = que.pop()
print(tmp,que)
['aaaa', 'a', 'b']
b ['aaaa', 'a']

上一篇:python中string.digits+string.ascii_letters用法 二


下一篇:Buried memory