Python 列表(List)操作方法詳解

list 是 Python 中的內置數據類型,它表示一種有序的元素集合。

創建列表:

您可以使用方括號 [] 創建列表,列表中的元素可以是任何數據類型。例如:

# 創建整數列表
numbers = [1, 2, 3, 4, 5]
print(numbers)

# 創建字符串列表
words = ['apple', 'banana', 'cherry']
print(words)

# 創建複雜數據類型列表
mixed = [1, 'apple', 3.14, [1, 2, 3]]
print(mixed)

運行以上代碼後,將得到以下輸出:

[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'apple', 3.14, [1, 2, 3]]

操作列表:

列表可以使用一些內置函數和方法來執行常見的操作,例如:

  • 訪問列表中的元素:您可以使用索引訪問列表中的元素,索引從 0 開始。例如:
words = ['apple', 'banana', 'cherry']
print(words[0]) # 輸出:apple

  • 修改列表中的元素:您可以使用索引修改列表中的元素。例如:
words = ['apple', 'banana', 'cherry']
words[1] = 'orange'
print(words) # 輸出:['apple', 'orange', 'cherry']

  • 添加元素:您可以使用 append 方法向列表末尾添加元素。例如:
words = ['apple', 'banana', 'cherry']
words.append('date')
print(words) # 輸出:['apple', 'banana', 'cherry', 'date']

  • 刪除元素:您可以使用 remove 方法刪除列表中的元素,該方法僅刪除列表中第一個匹配的元素。例如:
words = ['apple', 'banana', 'cherry']
words.remove('banana')
print(words) # 輸出:['apple', 'cherry']

這些僅是列表的一些常見操作,更多的內容可以在 Python 文檔中查找:https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

列表是 Python 中非常重要的數據類型,常常用於存儲多個元素。希望本篇文章對您有所幫助。

發布者:彬彬筆記,轉載請註明出處:https://www.binbinbiji.com/zh-hant/python/3034.html

(0)
彬彬筆記彬彬筆記
上一篇 2023年2月11日
下一篇 2023年2月12日

相關推薦

發表回復

登錄後才能評論
蜀ICP備14017386號-13