Python 中的序列資料型別是什麼?


序列資料型別用於在 Python 計算機語言 中的容器中儲存資料。用於儲存資料的不同型別的容器包括 列表元組字串。列表是可變的,可以儲存任何型別的資料,而字串是不可變的,只能儲存 str 型別的 資料。元組是不可變的資料型別,可以儲存任何型別的值。

列表

順序資料型別類包含列表資料型別。列表是順序類別中唯一的可變資料型別。它可以儲存任何資料型別的 值或元件。列表中的許多過程都可以更改和執行,例如 追加移除插入擴充套件反轉排序 等。我們還有更多 內建函式 來操縱列表。

示例

在下面的示例中,我們將瞭解如何建立列表以及如何使用索引訪問列表中的元素。這裡我們使用了普通索引和負索引。負索引表示從末尾開始,其中 -1 表示最後一個專案,-2 表示倒數第二個專案,依此類推。

List = ["Tutorialspoint", "is", "the", "best", "platform", "to", "learn", "new", "skills"] print(List) print("Accessing element from the list") print(List[0]) print(List[3]) print("Accessing element from the list by using negative indexing") print(List[-2]) print(List[-3])

輸出

以上程式碼產生以下結果

['Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills']
Accessing element from the list
Tutorialspoint
best
Accessing element from the list by using negative indexing
new
learn

字串

字串值使用字串資料型別儲存。我們無法操作字串中的元素,因為它不可變。字串有很多 內建函式,我們可以用它們來做很多事情。以下是一些內建字串函式 計數是否大寫是否小寫分割連線 等。

在 Python 中,可以使用單引號、雙引號,甚至三引號來建立字串。通常,我們使用三引號來建立多行字串。

示例

在下面的示例中,我們將瞭解如何建立字串以及如何使用索引訪問字串的字元。字串也支援負索引。

String = "Tutorialspoint is the best platform to learn new skills" print(String) print(type(String)) print("Accessing characters of a string:") print(String[6]) print(String[10]) print("Accessing characters of a string by using negative indexing") print(String[-6]) print(String[-21])

輸出

以上程式碼產生以下結果

Tutorialspoint is the best platform to learn new skills
<class 'str'>
Accessing characters of a string:
a
o
Accessing characters of a string by using negative indexing
s
m

元組

元組是一種屬於序列資料型別類別的資料型別。它們類似於 Python 中的列表,但具有不可變的屬性。我們無法更改元組的元素,但我們可以對它們執行 各種操作,例如計數、索引、型別等。

元組在 Python 中透過放置用逗號分隔的值序列來建立,可以使用或不使用括號進行資料分組。元組可以包含任意數量的元素和任意型別的資料(如字串、整數、列表等)。

示例

在下面的示例中,我們將瞭解如何建立元組以及如何使用索引訪問元組的元素。元組也支援負索引。

tuple = ('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills') print(tuple) print("Accessing elements of the tuple:") print(tuple[5]) print(tuple[2]) print("Accessing elements of the tuple by negative indexing: ") print(tuple[-6]) print(tuple[-1])

輸出

以上程式碼產生以下結果。

('Tutorialspoint', 'is', 'the', 'best', 'platform', 'to', 'learn', 'new', 'skills')
Accessing elements of the tuple:
to
the
Accessing elements of the tuple by negative indexing: 
best
skills

更新於: 2023-11-03

13K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.