」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 全面的 Python 資料結構備忘單

全面的 Python 資料結構備忘單

發佈於2024-08-02
瀏覽:733

Comprehensive Python Data Structures Cheat sheet

Comprehensive Python Data Structures Cheat sheet

Table of Contents

  1. Lists
  2. Tuples
  3. Sets
  4. Dictionaries
  5. Strings
  6. Arrays
  7. Stacks
  8. Queues
  9. Linked Lists
  10. Trees
  11. Heaps
  12. Graphs
  13. Advanced Data Structures

Lists

Lists are ordered, mutable sequences.

Creation

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]

Common Operations

# 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

Advanced Techniques

# 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

Tuples

Tuples are ordered, immutable sequences.

Creation

empty_tuple = ()
single_item_tuple = (1,)  # Note the comma
tuple_with_items = (1, 2, 3)
tuple_from_iterable = tuple("abc")

Common Operations

# 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)

Advanced Techniques

# 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'}

Sets

Sets are unordered collections of unique elements.

Creation

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}

Common Operations

# 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

Advanced Techniques

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

# Set comparisons
is_subset = set1 = set2
is_disjoint = set1.isdisjoint(set2)

# Set of sets (requires frozenset)
set_of_sets = {frozenset([1, 2]), frozenset([3, 4])}

Dictionaries

Dictionaries are mutable mappings of key-value pairs.

Creation

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)}

Common Operations

# 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

Advanced Techniques

# 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)]

Strings

Strings are immutable sequences of Unicode characters.

Creation

single_quotes = 'Hello'
double_quotes = "World"
triple_quotes = '''Multiline
string'''
raw_string = r'C:\Users\name'
f_string = f"The answer is {40   2}"

Common Operations

# 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')

Advanced Techniques

# 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'

Arrays

Arrays are compact sequences of numeric values (from the array module).

Creation and Usage

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()

Stacks

Stacks can be implemented using lists or collections.deque.

Implementation and Usage

# 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

Queues

Queues can be implemented using collections.deque or queue.Queue.

Implementation and Usage

# 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

Linked Lists

Python doesn't have a built-in linked list, but it can be implemented.

Simple Implementation

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)

Trees

Trees can be implemented using custom classes.

Simple Binary Tree Implementation

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 



Heaps

Heaps can be implemented using the heapq module.

Usage

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)

Graphs

Graphs can be implemented using dictionaries.

Simple Implementation

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)

Advanced Data Structures

Trie

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

Disjoint Set (Union-Find)

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[yroot] = xroot
        else:
            self.parent[yroot] = xroot
            self.rank[xroot]  = 1

This comprehensive cheatsheet covers a wide range of Python data structures, from the basic built-in types to more advanced custom implementations. Each section includes creation methods, common operations, and advanced techniques where applicable.
0

版本聲明 本文轉載於:https://dev.to/thelinuxman/comprehensive-python-data-structures-cheat-sheet-2j3p?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • JavaScript計算兩個日期之間天數的方法
    JavaScript計算兩個日期之間天數的方法
    How to Calculate the Difference Between Dates in JavascriptAs you attempt to determine the difference between two dates in Javascript, consider this s...
    程式設計 發佈於2025-04-26
  • 為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    為什麼不````''{margin:0; }`始終刪除CSS中的最高邊距?
    在CSS 問題:不正確的代碼: 全球範圍將所有餘量重置為零,如提供的代碼所建議的,可能會導致意外的副作用。解決特定的保證金問題是更建議的。 例如,在提供的示例中,將以下代碼添加到CSS中,將解決餘量問題: body H1 { 保證金頂:-40px; } 此方法更精確,避免了由全局保證金重置...
    程式設計 發佈於2025-04-26
  • 為什麼不使用CSS`content'屬性顯示圖像?
    為什麼不使用CSS`content'屬性顯示圖像?
    在Firefox extemers屬性為某些圖像很大,&& && && &&華倍華倍[華氏華倍華氏度]很少見,卻是某些瀏覽屬性很少,尤其是特定於Firefox的某些瀏覽器未能在使用內容屬性引用時未能顯示圖像的情況。這可以在提供的CSS類中看到:。 googlepic { 內容:url(&...
    程式設計 發佈於2025-04-26
  • 如何從PHP中的數組中提取隨機元素?
    如何從PHP中的數組中提取隨機元素?
    從陣列中的隨機選擇,可以輕鬆從數組中獲取隨機項目。考慮以下數組:; 從此數組中檢索一個隨機項目,利用array_rand( array_rand()函數從數組返回一個隨機鍵。通過將$項目數組索引使用此鍵,我們可以從數組中訪問一個隨機元素。這種方法為選擇隨機項目提供了一種直接且可靠的方法。
    程式設計 發佈於2025-04-26
  • 如何在無序集合中為元組實現通用哈希功能?
    如何在無序集合中為元組實現通用哈希功能?
    在未訂購的集合中的元素要糾正此問題,一種方法是手動為特定元組類型定義哈希函數,例如: template template template 。 struct std :: hash { size_t operator()(std :: tuple const&tuple)const {...
    程式設計 發佈於2025-04-26
  • 如何同步迭代並從PHP中的兩個等級陣列打印值?
    如何同步迭代並從PHP中的兩個等級陣列打印值?
    同步的迭代和打印值來自相同大小的兩個數組使用兩個數組相等大小的selectbox時,一個包含country代碼的數組,另一個包含鄉村代碼,另一個包含其相應名稱的數組,可能會因不當提供了exply for for for the uncore for the forsion for for ytry...
    程式設計 發佈於2025-04-26
  • HTML格式標籤
    HTML格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2025-04-26
  • 為什麼在我的Linux服務器上安裝Archive_Zip後,我找不到“ class \” class \'ziparchive \'錯誤?
    為什麼在我的Linux服務器上安裝Archive_Zip後,我找不到“ class \” class \'ziparchive \'錯誤?
    class'ziparchive'在Linux Server上安裝Archive_zip時找不到錯誤 commant in lin ins in cland ins in lin.11 on a lin.1 in a lin.11錯誤:致命錯誤:在... cass中找不到類z...
    程式設計 發佈於2025-04-26
  • CSS強類型語言解析
    CSS強類型語言解析
    您可以通过其强度或弱输入的方式对编程语言进行分类的方式之一。在这里,“键入”意味着是否在编译时已知变量。一个例子是一个场景,将整数(1)添加到包含整数(“ 1”)的字符串: result = 1 "1";包含整数的字符串可能是由带有许多运动部件的复杂逻辑套件无意间生成的。它也可以是故意从单个真理...
    程式設計 發佈於2025-04-26
  • 如何配置Pytesseract以使用數字輸出的單位數字識別?
    如何配置Pytesseract以使用數字輸出的單位數字識別?
    Pytesseract OCR具有單位數字識別和僅數字約束 在pytesseract的上下文中,在配置tesseract以識別單位數字和限制單個數字和限制輸出對數字可能會提出質疑。 To address this issue, we delve into the specifics of Te...
    程式設計 發佈於2025-04-26
  • 如何使用Regex在PHP中有效地提取括號內的文本
    如何使用Regex在PHP中有效地提取括號內的文本
    php:在括號內提取文本在處理括號內的文本時,找到最有效的解決方案是必不可少的。一種方法是利用PHP的字符串操作函數,如下所示: 作為替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式來搜索特...
    程式設計 發佈於2025-04-26
  • Python不會對超範圍子串切片報錯的原因
    Python不會對超範圍子串切片報錯的原因
    在python中用索引切片範圍:二重性和空序列索引單個元素不同,該元素會引起錯誤,切片在序列的邊界之外沒有。 這種行為源於索引和切片之間的基本差異。索引一個序列,例如“示例” [3],返回一個項目。但是,切片序列(例如“示例” [3:4])返回項目的子序列。 索引不存在的元素時,例如“示例” [9...
    程式設計 發佈於2025-04-26
  • 左連接為何在右表WHERE子句過濾時像內連接?
    左連接為何在右表WHERE子句過濾時像內連接?
    左JOIN CONUNDRUM:WITCHING小時在數據庫Wizard的領域中變成內在的加入很有趣,當將c.foobar條件放置在上面的Where子句中時,據說左聯接似乎會轉換為內部連接。僅當滿足A.Foo和C.Foobar標準時,才會返回結果。 為什麼要變形?關鍵在於其中的子句。當左聯接的右側...
    程式設計 發佈於2025-04-26
  • Java為何無法創建泛型數組?
    Java為何無法創建泛型數組?
    通用陣列創建錯誤 arrayList [2]; JAVA報告了“通用數組創建”錯誤。為什麼不允許這樣做? 答案:Create an Auxiliary Class:public static ArrayList<myObject>[] a = new ArrayList<my...
    程式設計 發佈於2025-04-26
  • 圖片在Chrome中為何仍有邊框? `border: none;`無效解決方案
    圖片在Chrome中為何仍有邊框? `border: none;`無效解決方案
    在chrome 中刪除一個頻繁的問題時,在與Chrome and IE9中的圖像一起工作時,遇到了一個頻繁的問題。和“邊境:無;”在CSS中。要解決此問題,請考慮以下方法: Chrome具有忽略“ border:none; none;”的已知錯誤,風格。要解決此問題,請使用以下CSS ID塊創建帶...
    程式設計 發佈於2025-04-26

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3