一、作用
1、反轉有序序列
2、修改原始序列
二、包名
1、collections
2、collections.abc
3、functools
4、more_itertools
5、sortedcontainers
三、collections.reverse詳解
1、反轉序列
from collections import deque
data = deque('abcde')
print(data)
# output: deque(['a', 'b', 'c', 'd', 'e'])
data.reverse()
print(data)
# output: deque(['e', 'd', 'c', 'b', 'a'])
deque可以輕鬆地處理字元串、列表和其他可迭代對象的反轉操作。
2、修改原始序列
a = [1, 2, 3, 4, 5, 6]
print(a)
# output: [1, 2, 3, 4, 5, 6]
a.reverse()
print(a)
# output: [6, 5, 4, 3, 2, 1]
reverse函數會直接修改原始序列的順序,並返回None。
3、關於處理鏈表的應用
class Node:
def __init__(self, value):
self.value = value
self.next_node = None
def __str__(self):
return f"Node({self.value})"
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.next_node = n2
n2.next_node = n3
print(n1)
# output: Node(1)
print(n1.next_node)
# output: Node(2)
print(n1.next_node.next_node)
# output: Node(3)
current = n1
nxt = None
prev = None
while current:
nxt = current.next_node
current.next_node = prev
prev = current
current = nxt
n1 = prev
print(n1)
# output: Node(3)
print(n1.next_node)
# output: Node(2)
print(n1.next_node.next_node)
# output: Node(1)
reverse函數的應用還可以用於處理鏈表數據結構,可以通過不斷更新前一個節點和當前節點達到反轉鏈表的效果。
鏈表的定義是一個指向下一個節點的引用,通過這個應用可以清晰地了解到reverse函數的應用。
原創文章,作者:EEWA,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/133603.html