当前位置:首页 > 文章列表 > 文章 > python教程 > 全面的 Python 数据结构备忘单

全面的 Python 数据结构备忘单

来源:dev.to 2024-07-18 10:19:01 0浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《全面的 Python 数据结构备忘单》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

全面的 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 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])}

词典

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

创建

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'

数组

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

创建和使用

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

以上就是《全面的 Python 数据结构备忘单》的详细内容,更多关于的资料请关注golang学习网公众号!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
JavaScript 中的控制台样式只有几千字节JavaScript 中的控制台样式只有几千字节
上一篇
JavaScript 中的控制台样式只有几千字节
高级 Python 概念:综合指南
下一篇
高级 Python 概念:综合指南
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • PubMedQA数据集详解:生物医学问答基准、功能与应用指南
    PubMedQA
    深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
    385次使用
  • H2O EvalGPT:开源LLM大模型评估与排行榜工具
    H2O EvalGPT
    H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
    462次使用
  • LMArena是什么?伯克利AI模型评估平台使用指南与功能解析
    LMArena
    LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
    473次使用
  • 斯坦福HELM:大语言模型Holistic Evaluation整体评估框架详解
    HELM
    深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
    410次使用
  • MMBench详解:多模态大模型基准测试、功能特点与使用指南
    MMBench
    MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
    237次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议 和 隐私政策
返回登录
  • 重置密码