搜尋
首頁後端開發Python教學掌握 Python 中的元組:綜合指南

元組是 Python 中重要的資料結構,提供了一種儲存有序且不可變資料集合的便捷方法。

在本部落格中,您將了解有關 Python 中元組的所有內容,包括建立、切片、方法等等。

讓我們直接開始吧! ?

Python 中的元組

元組是資料項的有序集合。在元組中,您可以將多個項目儲存在單一變數中。

元組是不可變的,即創建後您無法更改它們。

建立元組

元組使用圓括號 () 定義,項目之間以逗號分隔。

元組可以包含不同資料型別的項。

例如:

tuple1 = (1,2,36,3,15)
tuple2 = ("Red", "Yellow", "Blue")
tuple3 = (1, "John",12, 5.3)

print(tuple1) # (1, 2, 36, 3, 15)
print(tuple2) # ('Red', 'Yellow', 'Blue')
print(tuple3) # (1, 'John', 12, 5.3)

單項元組

要建立包含一項的元組,請在該項後面加上一個逗號。如果沒有逗號,Python 會將其視為整數類型。

例如:

tuple1 = (1) # This is an integer.
print(type(tuple1)) # <class>

tuple2 = (1,) # This is a tuple.
print(type(tuple2)) # <class>
</class></class>

元組長度

您可以使用 len() 函數來尋找元組的長度(元組中的項目數)。

例如:

tuple1 = (1,2,36,3,15)
lengthOfTuple = len(tuple1)

print(lengthOfTuple) # 5

訪問元組項

您可以使用索引存取元組項目/元素。每個元素都有其唯一的索引。

第一個元素的索引從 0 開始,第二個元素的索引從 1 開始,依此類推。

例如:

fruits = ("Orange", "Apple", "Banana")

print(fruits[0]) # Orange
print(fruits[1]) # Apple
print(fruits[2]) # Banana

您也可以從元組末尾存取元素(-1 表示最後一個元素,-2 表示倒數第二個元素,依此類推),稱為負索引

例如:

fruits = ("Orange", "Apple", "Banana")

print(fruits[-1]) # Banana 
print(fruits[-2]) # Apple
print(fruits[-3]) # Orange
# for understanding, you can consider this as fruits[len(fruits)-3]

檢查元組中是否存在某個項目

您可以使用 in 關鍵字檢查元組中是否存在某個元素。

範例1:

fruits = ("Orange", "Apple", "Banana")
if "Orange" in fruits:
    print("Orange is in the tuple.")
else:
    print("Orange is not in the tuple.")

#Output: Orange is in the tuple.

範例2:

numbers = (1, 57, 13)
if 7 in numbers:
    print("7 is in the tuple.")
else:
    print("7 is not in the tuple.")

# Output: 7 is not in the tuple.

元組切片

您可以透過給出開始、結束和跳躍(跳過)參數來取得一系列元組項目。

文法:

tupleName[start : end : jumpIndex]

注意:跳轉索引是可選的。

範例1:

# Printing elements within a particular range
numbers = (1, 57, 13, 6, 18, 54)

# using positive indexes(this will print the items starting from index 2 and ending at index 4 i.e. (5-1))
print(numbers[2:5]) 

# using negative indexes(this will print the items starting from index -5 and ending at index -3 i.e. (-2-1))
print(numbers[-5:-2])   

輸出:

(13, 6, 18)
(57, 13, 6)

範例2:

當沒有提供結束索引時,解釋器將列印直到末尾的所有值。

# Printing all elements from a given index to till the end
numbers = (1, 57, 13, 6, 18, 54)

# using positive indexes
print(numbers[2:])  

# using negative indexes
print(numbers[-5:]) 

輸出:

(13, 6, 18, 54)
(57, 13, 6, 18, 54)

範例3:

當沒有提供開始索引時,解釋器會列印從開始到提供的結束索引的所有值。

# Printing all elements from start to a given index
numbers = (1, 57, 13, 6, 18, 54)

#using positive indexes
print(numbers[:4])  

#using negative indexes
print(numbers[:-2]) 

輸出:

(1, 57, 13, 6)
(1, 57, 13, 6)

範例 4:

您可以透過給予跳轉索引來列印替代值。

# Printing alternate values
numbers = (1, 57, 13, 6, 18, 54)

# using positive indexes(here start and end indexes are not given and 2 is jump index.)
print(numbers[::2]) 

# using negative indexes(here start index is -2, end index is not given and 2 is jump index.)
print(numbers[-2::2])   

輸出:

(1, 13, 18)
(18)

操作元組

元組不可變,因此無法新增、刪除或變更項目。但是,您可以將元組轉換為列表,修改列表,然後將其轉換回元組。

例如:

tuple1 = (1,2,36,3,15)
tuple2 = ("Red", "Yellow", "Blue")
tuple3 = (1, "John",12, 5.3)

print(tuple1) # (1, 2, 36, 3, 15)
print(tuple2) # ('Red', 'Yellow', 'Blue')
print(tuple3) # (1, 'John', 12, 5.3)

連結元組

您可以使用運算子連接兩個元組。

例如:

tuple1 = (1) # This is an integer.
print(type(tuple1)) # <class>

tuple2 = (1,) # This is a tuple.
print(type(tuple2)) # <class>
</class></class>

輸出:

tuple1 = (1,2,36,3,15)
lengthOfTuple = len(tuple1)

print(lengthOfTuple) # 5

元組方法

Tuple 有以下內建方法:

數數()

此方法傳回元素在元組中出現的次數。

文法:

fruits = ("Orange", "Apple", "Banana")

print(fruits[0]) # Orange
print(fruits[1]) # Apple
print(fruits[2]) # Banana

例如:

fruits = ("Orange", "Apple", "Banana")

print(fruits[-1]) # Banana 
print(fruits[-2]) # Apple
print(fruits[-3]) # Orange
# for understanding, you can consider this as fruits[len(fruits)-3]

指數()

此方法傳回元組中給定元素的第一次出現。

注意:如果在元組中找不到該元素,此方法會引發 ValueError。

例如:

fruits = ("Orange", "Apple", "Banana")
if "Orange" in fruits:
    print("Orange is in the tuple.")
else:
    print("Orange is not in the tuple.")

#Output: Orange is in the tuple.

您可以為搜尋指定起始索引。例如:

numbers = (1, 57, 13)
if 7 in numbers:
    print("7 is in the tuple.")
else:
    print("7 is not in the tuple.")

# Output: 7 is not in the tuple.

今天就這些。

希望對您有幫助。

感謝您的閱讀。

我在學習 Python 語言時創建了詳細的 Python 筆記,而且只需 1 美元!在這裡獲取它們:立即下載

有關更多此類內容,請點擊此處。

在 X(Twitter) 上追蹤我,取得日常 Web 開發技巧。

繼續編碼! !

Mastering Tuples in Python: A Comprehensive Guide

以上是掌握 Python 中的元組:綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何解決Linux終端中查看Python版本時遇到的權限問題?如何解決Linux終端中查看Python版本時遇到的權限問題?Apr 01, 2025 pm 05:09 PM

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

如何使用Python創建命令行接口(CLI)?如何使用Python創建命令行接口(CLI)?Mar 10, 2025 pm 06:48 PM

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中?Apr 01, 2025 pm 11:15 PM

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

哪些流行的Python庫及其用途?哪些流行的Python庫及其用途?Mar 21, 2025 pm 06:46 PM

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

解釋Python中虛擬環境的目的。解釋Python中虛擬環境的目的。Mar 19, 2025 pm 02:27 PM

文章討論了虛擬環境在Python中的作用,重點是管理項目依賴性並避免衝突。它詳細介紹了他們在改善項目管理和減少依賴問題方面的創建,激活和利益。

什麼是正則表達式?什麼是正則表達式?Mar 20, 2025 pm 06:25 PM

正則表達式是在編程中進行模式匹配和文本操作的強大工具,從而提高了各種應用程序的文本處理效率。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中