Python 元組

元組是不同數據類型的元素的不可變(不可改變)集合。這是一個有序集合,因此它保留了元素定義的順序。

元組由括弧()中的元素定義,用逗號分隔。 下面聲明一個元組類型變數。

Example: Tuple Variable Declaration

tpl=() # empty tuple
print(tpl)

names = ('Jeff', 'Bill', 'Steve', 'Yash') # string tuple
print(names)

nums = (1, 2, 3, 4, 5) # int tuple
print(nums)

employee=(1, 'Steve', True, 25, 12000)  # heterogeneous data tuple
print(employee) 

Output:

()
('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000) 

但是,不必將元組元素括在括弧中。元組對象可以包括由逗號分隔的元素,沒有括弧。

Example: Tuple Variable Declaration

names = 'Jeff', 'Bill', 'Steve', 'Yash' # string tuple
print(names)

nums = 1, 2, 3, 4, 5 # int tuple
print(nums)

employee=1, 'Steve', True, 25, 12000  # heterogeneous data tuple
print(employee) 

Output:

('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000) 

除非後跟逗號,否則元組不能用單個元素聲明。

Example: Tuple Variable Declaration

names = ('Jeff') # considered as string type
print(names)
print(type(names))

names = ('Jeff',) # tuple with single element
print(names)
print(type(names)) 

Output:

'Jeff'
<class 'string'>
(Jeff)
<class 'tuple'> 

訪問元組元素

元組中的每個元素都由方括弧[]中的索引訪問。索引以零開始,以(元素數- 1)結束,如下所示。

Example: Access Tuple Elements using Indexes

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[0]) # prints 'Jeff'
print(names[1]) # prints 'Bill'
print(names[2]) # prints 'Steve'
print(names[3]) # prints 'Yash'

nums = (1, 2, 3, 4, 5) 
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5 

Output:

Jeff
Bill
Steve
Yash
1
2
5 

元組也支持負索引,與列表類型相同。第一個元素的負指數從-number of elements開始,最後一個元素以-1 結束。

Example: Negative Indexing

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[-4]) # prints 'Jeff'
print(names[-3]) # prints 'Bill'
print(names[-2]) # prints 'Steve'
print(names[-1]) # prints 'Yash' 

Output:

Jeff
Bill
Steve
Yash 

如果指定索引處的元素不存在,則將引發錯誤「索引超出範圍」。

>>> names[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range 

元組元素可以被解包並分配給變數,如下所示。但是,變數的數量必須與元組中元素的數量相匹配;否則,將引發錯誤。

Example: Access Tuple Elements using Indexes

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
a, b, c, d = names # unpack tuple
print(a, b, c, d) 

Output:

Jeff Bill Steve Yash 

更新或刪除元組元素

元組是不可更改的。因此,一旦創建了元組,任何試圖改變其內容的操作都是不允許的。例如,試圖修改或刪除names元組的元素將導致錯誤。

>>> names = ('Jeff', 'Bill', 'Steve', 'Yash') 
>>> names[0] = 'Swati'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del names[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion 

但是,您可以使用del關鍵字刪除整個元組。

>>> del names

元組類

元組的基礎類型是元組類。使用type()功能檢查變數的類型。

Example: Tuple Variable Declaration

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print('names type: ', type(names))

nums = (1,2,3,4,5) 
print('nums type: ', type(nums)) 

Output:

names type: <class 'tuple'>
nums type: <class 'tuple'> 

tuple()構造器用於將任何可迭代類型轉換為元組類型。

Example: Tuple Variable Declaration

tpl = tuple('Hello') # converts string to tuple
print(tpl)
tpl = tuple([1,2,3,4,5]) # converts list to tuple
print(tpl)
tpl = tuple({1,2,3,4,5}) # converts set to tuple
print(tpl)
tpl = tuple({1:"One",2:"Two"}) # converts dictionary to tuple
print(tpl) 

Output:

('H','e','l','l','o')
(1,2,3,4,5)
(1,2,3,4,5)
(1,2) 

元組運算

像字元串一樣,元組對象也是一個序列。因此,用於字元串的運算符也可用於元組。

操作員例子
+ 運算符返回包含第一個和第二個元組對象的所有元素的元組。
>>> t1=(1,2,3)
>>> t2=(4,5,6)         
>>> t1+t2              
(1, 2, 3, 4, 5, 6) 
>>> t2+(7,)            
(4, 5, 6, 7)

|
| ***** 運算符連接同一個元組的多個副本。 |

>>> t1=(1,2,3)
>>> t1*4                             
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

|
| [] 運算符返回給定索引處的項目。負索引從右側開始計算位置。 |

>>> t1=(1,2,3,4,5,6)     
>>> t1[3]                
4                        
>>> t1[-2]               
5

|
| [:] 運算符返回由兩個索引操作數指定的範圍內的項目,這兩個索引操作數由:符號分隔。
如果省略第一個操作數,範圍從零開始。 如果省略第二個操作數,範圍將上升到元組的末尾。 |

>>> t1=(1,2,3,4,5,6) 
>>> t1[1:3]              
(2, 3)                   
>>> t1[3:]               
(4, 5, 6)                
>>> t1[:3]               
(1, 2, 3)

|
| 如果給定元組中存在某項,則運算符中的返回真。 |

>>> t1=(1,2,3,4,5,6) 
>>> 5 in t1
True                
>>> 10 in t1 
False

|
| 如果給定元組中不存在某項,則不在運算符中的返回真。 |

>>> t1=(1,2,3,4,5,6) 
>>> 4 not in t1 
False                    
>>> 10 not in t1
True

|

原創文章,作者:PIHFQ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/329809.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
PIHFQ的頭像PIHFQ
上一篇 2025-01-14 18:55
下一篇 2025-01-14 18:55

相關推薦

  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29

發表回復

登錄後才能評論