當一般字串變數無法處理資料儲存,涉及到串列(list)和元組(tuple)時,Python 提供了內建的資料結構來處理這些操作。以下是一個簡單的教學,其中包含了一些常見的列表和元組操作,並附上相關的範例程式碼。

  1. 串列建立
    在 Python 中,你可以使用方括號 [] 來建立串列。

     list1 = [1, 2, 3, 4, 5]
     list2 = ['apple', 'banana', 'orange']
    
  2. 元組建立
    在 Python 中,你可以使用圓括號 () 來建立元組。

     tuple1 = (1, 2, 3, 4, 5)
     tuple2 = ('apple', 'banana', 'orange')
    
  3. 串列和元組的存取
    你可以使用索引 (index) 來存取串列和元組中的元素。注意索引從 0 開始,最後一個元素的索引是資料結構的長度減一。

     print(list1[0])     # 輸出: 1
     print(tuple2[2])    # 輸出: orange
    
  4. 串列和元組的切片
    你可以使用切片 (slicing) 來獲取串列和元組的子集。

     print(list1[1:4])     # 輸出: [2, 3, 4]
     print(tuple2[:2])     # 輸出: ('apple', 'banana')
    
  5. 串列的修改
    串列是可變的資料結構,你可以通過索引進行修改、新增或刪除元素。

     list1[0] = 10
     print(list1)     # 輸出: [10, 2, 3, 4, 5]
    
     list1.append(6)
     print(list1)     # 輸出: [10, 2, 3, 4, 5, 6]
    
     del list1[2]
     print(list1)     # 輸出: [10, 2, 4, 5, 6]
    
  6. 元組的不可變性
    元組是不可變的資料結構,一旦建立就不能修改其中的元素。

     # 嘗試修改元組元素會產生錯誤
     tuple1[0] = 100  # 產生 TypeError
    
  7. 串列和元組的迭代
    你可以使用迴圈來遍歷串列和元組中的元素。

     for item in list2:
         print(item)
    
     for item in tuple2:
         print(item)
    
  8. 串列和元組的長度
    你可以使用 len() 函式來獲取串列和元組的長度。

     print(len(list1))     # 輸出: 5
     print(len(tuple2))    # 輸出: 3
    

以上是一些 Python 中處理串列和元組的基本操作。Python 還提供了許多其他有用的方法和函式,可用於進一步處理串列和元組。希望這個教學能幫助你入門串列和元組的基礎操作!

#Python







你可能感興趣的文章

MTR04_1018

MTR04_1018

form - input

form - input

Vite系列#編譯設定

Vite系列#編譯設定






留言討論