python语法:
一、通常使用列表(list)来实现栈。append(),pop()
点击查看代码
stack = []
# 压栈(push)
stack.append(1)
# 弹栈(pop)
top_element = stack.pop()
# 查看栈顶元素(peek)
top_element = stack[-1]
# 检查栈是否为空
is_empty = len(stack) == 0
点击查看代码
# 出队(dequeue)区别:先进先出
front_element = queue.pop(0)
# 查看队首元素(peek)
front_element = queue[0]
- 列表[]:append(),pop()
- 字典{}:dict['xx']=4
- 集合{}:add(),remove()
- 元组():不可变?
点击查看代码
# 高端数据结构'deque'双端队列
from collections import deque
my_deque = deque([1, 2, 3, 4, 5])
my_deque.append(6) # 输出: deque([1, 2, 3, 4, 5, 6])
my_deque.appendleft(0) # 输出: deque([0, 1, 2, 3, 4, 5, 6])
my_deque.pop() # 输出: deque([0, 1, 2, 3, 4, 5])
my_deque.popleft() # 输出: deque([1, 2, 3, 4, 5])
# 用于计数的字典'Counter'
from collections import Counter
my_counter = Counter(['a', 'b', 'c', 'a', 'b', 'a'])
print(my_counter) # 输出: Counter({'a': 3, 'b': 2, 'c': 1})
print(my_counter.most_common(2)) # 输出: [('a', 3), ('b', 2)]