PHP前端开发

全面的 Python 数据结构备忘单

百变鹏仔 2年前 (2025-01-16) #Python
文章标签 数据结构

全面的 python 数据结构备忘单

目录

  1. 列表
  2. 元组
  3. 套装
  4. 词典
  5. 弦乐
  6. 数组
  7. 堆栈
  8. 排队
  9. 链接列表
  10. 树
  11. 堆
  12. 图表
  13. 高级数据结构

列表

列表是有序的、可变的序列。

创建

empty_list = []list_with_items = [1, 2, 3]list_from_iterable = list("abc")list_comprehension = [x for x in range(10) if x % 2 == 0]

常用操作

# accessing elementsfirst_item = my_list[0]last_item = my_list[-1]# slicingsubset = my_list[1:4]  # elements 1 to 3reversed_list = my_list[::-1]# adding elementsmy_list.append(4)  # add to endmy_list.insert(0, 0)  # insert at specific indexmy_list.extend([5, 6, 7])  # add multiple elements# removing elementsremoved_item = my_list.pop()  # remove and return last itemmy_list.remove(3)  # remove first occurrence of 3del my_list[0]  # remove item at index 0# other operationslength = len(my_list)index = my_list.index(4)  # find index of first occurrence of 4count = my_list.count(2)  # count occurrences of 2my_list.sort()  # sort in placesorted_list = sorted(my_list)  # return new sorted listmy_list.reverse()  # reverse in place

先进技术

# list as stackstack = [1, 2, 3]stack.append(4)  # pushtop_item = stack.pop()  # pop# list as queue (not efficient, use collections.deque instead)queue = [1, 2, 3]queue.append(4)  # enqueuefirst_item = queue.pop(0)  # dequeue# nested listsmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]flattened = [item for sublist in matrix for item in sublist]# list multiplicationrepeated_list = [0] * 5  # [0, 0, 0, 0, 0]# list unpackinga, *b, c = [1, 2, 3, 4, 5]  # a=1, b=[2, 3, 4], c=5

元组

元组是有序的、不可变的序列。

创建

empty_tuple = ()single_item_tuple = (1,)  # note the commatuple_with_items = (1, 2, 3)tuple_from_iterable = tuple("abc")

常用操作

# accessing elements (similar to lists)first_item = my_tuple[0]last_item = my_tuple[-1]# slicing (similar to lists)subset = my_tuple[1:4]# other operationslength = len(my_tuple)index = my_tuple.index(2)count = my_tuple.count(3)# tuple unpackinga, b, c = (1, 2, 3)

先进技术

# named tuplesfrom collections import namedtuplepoint = namedtuple('point', ['x', 'y'])p = point(11, y=22)print(p.x, p.y)# tuple as dictionary keys (immutable, so allowed)dict_with_tuple_keys = {(1, 2): 'value'}

套

集合是独特元素的无序集合。

创建

empty_set = set()set_with_items = {1, 2, 3}set_from_iterable = set([1, 2, 2, 3, 3])  # {1, 2, 3}set_comprehension = {x for x in range(10) if x % 2 == 0}

常用操作

# adding elementsmy_set.add(4)my_set.update([5, 6, 7])# removing elementsmy_set.remove(3)  # raises keyerror if not foundmy_set.discard(3)  # no error if not foundpopped_item = my_set.pop()  # remove and return an arbitrary element# other operationslength = len(my_set)is_member = 2 in my_set# set operationsunion = set1 | set2intersection = set1 & set2difference = set1 - set2symmetric_difference = set1 ^ set2

先进技术

# frozen sets (immutable)frozen = frozenset([1, 2, 3])# set comparisonsis_subset = set1 <= set2is_superset = set1 >= set2is_disjoint = set1.isdisjoint(set2)# set of sets (requires frozenset)set_of_sets = {frozenset([1, 2]), frozenset([3, 4])}

词典

字典是键值对的可变映射。

立即学习“Python免费学习笔记(深入)”;

创建

empty_dict = {}dict_with_items = {'a': 1, 'b': 2, 'c': 3}dict_from_tuples = dict([('a', 1), ('b', 2), ('c', 3)])dict_comprehension = {x: x**2 for x in range(5)}

常用操作

# accessing elementsvalue = my_dict['key']value = my_dict.get('key', default_value)# adding/updating elementsmy_dict['new_key'] = valuemy_dict.update({'key1': value1, 'key2': value2})# removing elementsdel my_dict['key']popped_value = my_dict.pop('key', default_value)last_item = my_dict.popitem()  # remove and return an arbitrary key-value pair# other operationskeys = my_dict.keys()values = my_dict.values()items = my_dict.items()length = len(my_dict)is_key_present = 'key' in my_dict

先进技术

# dictionary unpackingmerged_dict = {**dict1, **dict2}# default dictionariesfrom collections import defaultdictdd = defaultdict(list)dd['key'].append(1)  # no keyerror# ordered dictionaries (python 3.7+ dictionaries are ordered by default)from collections import ordereddictod = ordereddict([('a', 1), ('b', 2), ('c', 3)])# counterfrom collections import counterc = counter(['a', 'b', 'c', 'a', 'b', 'b'])print(c.most_common(2))  # [('b', 3), ('a', 2)]

弦乐

字符串是不可变的 unicode 字符序列。

创建

single_quotes = 'hello'double_quotes = "world"triple_quotes = '''multilinestring'''raw_string = r'c:usersame'f_string = f"the answer is {40 + 2}"

常用操作

# accessing charactersfirst_char = my_string[0]last_char = my_string[-1]# slicing (similar to lists)substring = my_string[1:4]# string methodsupper_case = my_string.upper()lower_case = my_string.lower()stripped = my_string.strip()split_list = my_string.split(',')joined = ', '.join(['a', 'b', 'c'])# other operationslength = len(my_string)is_substring = 'sub' in my_stringchar_count = my_string.count('a')

先进技术

# string formattingformatted = "{} {}".format("hello", "world")formatted = "%s %s" % ("hello", "world")# regular expressionsimport repattern = r'd+'matches = re.findall(pattern, my_string)# unicode handlingunicode_string = u'u0061u0062u0063'

数组

数组是紧凑的数值序列(来自数组模块)。

创建和使用

from array import arrayint_array = array('i', [1, 2, 3, 4, 5])float_array = array('f', (1.0, 1.5, 2.0, 2.5))# operations (similar to lists)int_array.append(6)int_array.extend([7, 8, 9])popped_value = int_array.pop()

堆栈

堆栈可以使用lists或collections.deque来实现。

实施和使用

# using liststack = []stack.append(1)  # pushstack.append(2)top_item = stack.pop()  # pop# using deque (more efficient)from collections import dequestack = deque()stack.append(1)  # pushstack.append(2)top_item = stack.pop()  # pop

队列

队列可以使用collections.deque或queue.queue来实现。

实施和使用

# using dequefrom collections import dequequeue = deque()queue.append(1)  # enqueuequeue.append(2)first_item = queue.popleft()  # dequeue# using queue (thread-safe)from queue import queueq = queue()q.put(1)  # enqueueq.put(2)first_item = q.get()  # dequeue

链表

python没有内置链表,但可以实现。

实施简单

class node:    def __init__(self, data):        self.data = data        self.next = noneclass linkedlist:    def __init__(self):        self.head = none    def append(self, data):        if not self.head:            self.head = node(data)            return        current = self.head        while current.next:            current = current.next        current.next = node(data)

树木

树可以使用自定义类来实现。

简单的二叉树实现

class treenode:    def __init__(self, value):        self.value = value        self.left = none        self.right = noneclass binarytree:    def __init__(self, root):        self.root = treenode(root)    def insert(self, value):        self._insert_recursive(self.root, value)    def _insert_recursive(self, node, value):        if value < node.value:            if node.left is none:                node.left = treenode(value)            else:                self._insert_recursive(node.left, value)        else:            if node.right is none:                node.right = treenode(value)            else:                self._insert_recursive(node.right, value)

堆

堆可以使用 heapq 模块来实现。

用法

import heapq# create a heapheap = []heapq.heappush(heap, 3)heapq.heappush(heap, 1)heapq.heappush(heap, 4)# pop smallest itemsmallest = heapq.heappop(heap)# create a heap from a listmy_list = [3, 1, 4, 1, 5, 9]heapq.heapify(my_list)

图表

图可以使用字典来实现。

实施简单

class graph:    def __init__(self):        self.graph = {}    def add_edge(self, u, v):        if u not in self.graph:            self.graph[u] = []        self.graph[u].append(v)    def bfs(self, start):        visited = set()        queue = [start]        visited.add(start)        while queue:            vertex = queue.pop(0)            print(vertex, end=' ')            for neighbor in self.graph.get(vertex, []):                if neighbor not in visited:                    visited.add(neighbor)                    queue.append(neighbor)

高级数据结构

特里树

class trienode:    def __init__(self):        self.children = {}        self.is_end = falseclass trie:    def __init__(self):        self.root = trienode()    def insert(self, word):        node = self.root        for char in word:            if char not in node.children:                node.children[char] = trienode()            node = node.children[char]        node.is_end = true    def search(self, word):        node = self.root        for char in word:            if char not in node.children:                return false            node = node.children[char]        return node.is_end

不相交集(并查集)

class DisjointSet:    def __init__(self, vertices):        self.parent = {v: v for v in vertices}        self.rank = {v: 0 for v in vertices}    def find(self, item):        if self.parent[item] != item:            self.parent[item] = self.find(self.parent[item])        return self.parent[item]    def union(self, x, y):        xroot = self.find(x)        yroot = self.find(y)        if self.rank[xroot] < self.rank[yroot]:            self.parent[xroot] = yroot        elif self.rank[xroot] > self.rank[yroot]:            self.parent[yroot] = xroot        else:            self.parent[yroot] = xroot            self.rank[xroot] += 1

这份全面的备忘单涵盖了广泛的 python 数据结构,从基本的内置类型到更高级的自定义实现。每个部分都包含创建方法、常用操作以及适用的高级技巧。
0