0

0

全面的 Python 数据结构备忘单

王林

王林

发布时间:2024-07-18 10:31:01

|

863人浏览过

|

来源于dev.to

转载

全面的 python 数据结构备忘单

全面的 python 数据结构备忘单

目录

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

列表

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

创建

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 elements
first_item = my_list[0]
last_item = my_list[-1]

# slicing
subset = my_list[1:4]  # elements 1 to 3
reversed_list = my_list[::-1]

# adding elements
my_list.append(4)  # add to end
my_list.insert(0, 0)  # insert at specific index
my_list.extend([5, 6, 7])  # add multiple elements

# removing elements
removed_item = my_list.pop()  # remove and return last item
my_list.remove(3)  # remove first occurrence of 3
del my_list[0]  # remove item at index 0

# other operations
length = len(my_list)
index = my_list.index(4)  # find index of first occurrence of 4
count = my_list.count(2)  # count occurrences of 2
my_list.sort()  # sort in place
sorted_list = sorted(my_list)  # return new sorted list
my_list.reverse()  # reverse in place

先进技术

# list as stack
stack = [1, 2, 3]
stack.append(4)  # push
top_item = stack.pop()  # pop

# list as queue (not efficient, use collections.deque instead)
queue = [1, 2, 3]
queue.append(4)  # enqueue
first_item = queue.pop(0)  # dequeue

# nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for sublist in matrix for item in sublist]

# list multiplication
repeated_list = [0] * 5  # [0, 0, 0, 0, 0]

# list unpacking
a, *b, c = [1, 2, 3, 4, 5]  # a=1, b=[2, 3, 4], c=5

元组

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

创建

empty_tuple = ()
single_item_tuple = (1,)  # note the comma
tuple_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 operations
length = len(my_tuple)
index = my_tuple.index(2)
count = my_tuple.count(3)

# tuple unpacking
a, b, c = (1, 2, 3)

先进技术

# named tuples
from collections import namedtuple
point = 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 elements
my_set.add(4)
my_set.update([5, 6, 7])

# removing elements
my_set.remove(3)  # raises keyerror if not found
my_set.discard(3)  # no error if not found
popped_item = my_set.pop()  # remove and return an arbitrary element

# other operations
length = len(my_set)
is_member = 2 in my_set

# set operations
union = set1 | set2
intersection = set1 & set2
difference = set1 - set2
symmetric_difference = set1 ^ set2

先进技术

# frozen sets (immutable)
frozen = frozenset([1, 2, 3])

# set comparisons
is_subset = set1 <= set2
is_superset = set1 >= set2
is_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 elements
value = my_dict['key']
value = my_dict.get('key', default_value)

# adding/updating elements
my_dict['new_key'] = value
my_dict.update({'key1': value1, 'key2': value2})

# removing elements
del 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 operations
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
length = len(my_dict)
is_key_present = 'key' in my_dict

先进技术

# dictionary unpacking
merged_dict = {**dict1, **dict2}

# default dictionaries
from collections import defaultdict
dd = defaultdict(list)
dd['key'].append(1)  # no keyerror

# ordered dictionaries (python 3.7+ dictionaries are ordered by default)
from collections import ordereddict
od = ordereddict([('a', 1), ('b', 2), ('c', 3)])

# counter
from collections import counter
c = 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 = '''multiline
string'''
raw_string = r'c:\users\name'
f_string = f"the answer is {40 + 2}"

常用操作

# accessing characters
first_char = my_string[0]
last_char = my_string[-1]

# slicing (similar to lists)
substring = my_string[1:4]

# string methods
upper_case = my_string.upper()
lower_case = my_string.lower()
stripped = my_string.strip()
split_list = my_string.split(',')
joined = ', '.join(['a', 'b', 'c'])

# other operations
length = len(my_string)
is_substring = 'sub' in my_string
char_count = my_string.count('a')

先进技术

# string formatting
formatted = "{} {}".format("hello", "world")
formatted = "%s %s" % ("hello", "world")

# regular expressions
import re
pattern = r'\d+'
matches = re.findall(pattern, my_string)

# unicode handling
unicode_string = u'\u0061\u0062\u0063'

数组

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

Ztoy网络商铺多用户版
Ztoy网络商铺多用户版

在原版的基础上做了一下修正:增加1st在线支付功能与论坛用户数据结合,vip也可与论坛相关,增加互动性vip会员的全面修正评论没有提交正文的问题特价商品的调用连接问题删掉了2个木马文件去掉了一个后门补了SQL注入补了一个过滤漏洞浮动价不能删除的问题不能够搜索问题收藏时放入购物车时出错点放入购物车弹出2个窗口修正定单不能删除问题VIP出错问题主题添加问题商家注册页导航连接问题添加了导航FLASH源文

下载

创建和使用

from array import array
int_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 list
stack = []
stack.append(1)  # push
stack.append(2)
top_item = stack.pop()  # pop

# using deque (more efficient)
from collections import deque
stack = deque()
stack.append(1)  # push
stack.append(2)
top_item = stack.pop()  # pop

队列

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

实施和使用

# using deque
from collections import deque
queue = deque()
queue.append(1)  # enqueue
queue.append(2)
first_item = queue.popleft()  # dequeue

# using queue (thread-safe)
from queue import queue
q = queue()
q.put(1)  # enqueue
q.put(2)
first_item = q.get()  # dequeue

链表

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

实施简单

class node:
    def __init__(self, data):
        self.data = data
        self.next = none

class 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 = none

class 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 heap
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 4)

# pop smallest item
smallest = heapq.heappop(heap)

# create a heap from a list
my_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 = false

class 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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

298

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

212

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1501

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

624

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

613

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

588

2024.04.29

go语言字符串相关教程
go语言字符串相关教程

本专题整合了go语言字符串相关教程,阅读专题下面的文章了解更多详细内容。

171

2025.07.29

c++字符串相关教程
c++字符串相关教程

本专题整合了c++字符串相关教程,阅读专题下面的文章了解更多详细内容。

83

2025.08.07

俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

158

2026.01.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.3万人学习

Django 教程
Django 教程

共28课时 | 3.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号