Stories

Detail Return Return

Python中數組示例代碼 - Stories Detail

Python中數組示例代碼

Python中,數組通常使用列表(list)來實現。以下是一個簡單的數組示例,包括創建、訪問和修改數組元素的操作。

python
# 創建數組  
arr = [1, 2, 3, 4, 5]  
  
# 訪問數組元素  
print("第一個元素:", arr[0])  # 輸出: 第一個元素: 1  
print("第三個元素:", arr[2])  # 輸出: 第三個元素: 3  
  
# 修改數組元素  
arr[1] = 10  
print("修改後的數組:", arr)  # 輸出: 修改後的數組: [1, 10, 3, 4, 5]  
  
# 在數組末尾添加元素  
arr.append(6)  
print("添加元素後的數組:", arr)  # 輸出: 添加元素後的數組: [1, 10, 3, 4, 5, 6]  
  
# 刪除數組元素  
arr.remove(3)  
print("刪除元素後的數組:", arr)  # 輸出: 刪除元素後的數組: [1, 10, 4, 5, 6]

鏈表示例代碼

鏈表是一種常見的數據結構,Python中的鏈表通常通過自定義類來實現。以下是一個簡單的單向鏈表示例,包括創建、插入和遍歷鏈表的操作。

python
class Node:  
    def __init__(self, data=None):  
        self.data = data  
        self.next = None  
  
  
class LinkedList:  
    def __init__(self):  
        self.head = None  
  
    def insert(self, data):  
        if not self.head:  
            self.head = Node(data)  
        else:  
            cur = self.head  
            while cur.next:  
                cur = cur.next  
            cur.next = Node(data)  
  
    def print_list(self):  
        cur = self.head  
        while cur:  
            print(cur.data)  
            cur = cur.next  
  
  
# 創建鏈表並插入元素  
linked_list = LinkedList()  
linked_list.insert(1)  
linked_list.insert(2)  
linked_list.insert(3)  
  
# 遍歷鏈表並打印元素  
linked_list.print_list()  # 輸出: 1 2 3

這個示例中,Node 類表示鏈表中的一個節點,包含一個數據元素和一個指向下一個節點的指針。LinkedList 類表示整個鏈表,包含一個指向鏈表頭部的指針,以及插入元素和遍歷鏈表的方法。

Add a new Comments

Some HTML is okay.