(Python基礎(chǔ)教程之九)Python中的Tuple操作

  1. Python基礎(chǔ)教程
  2. 在SublimeEditor中配置Python環(huán)境
  3. Python代碼中添加注釋
  4. Python中的變量的使用
  5. Python中的數(shù)據(jù)類型
  6. Python中的關(guān)鍵字
  7. Python字符串操作
  8. Python中的list操作
  9. Python中的Tuple操作
  10. Pythonmax()和min()–在列表或數(shù)組中查找最大值和最小值
  11. Python找到最大的N個(前N個)或最小的N個項目
  12. Python讀寫CSV文件
  13. Python中使用httplib2–HTTPGET和POST示例
  14. Python將tuple開箱為變量或參數(shù)
  15. Python開箱Tuple–太多值無法解壓
  16. Pythonmultidict示例–將單個鍵映射到字典中的多個值
  17. PythonOrderedDict–有序字典
  18. Python字典交集–比較兩個字典
  19. Python優(yōu)先級隊列示例

Pyhton中元組類似于不變,list但不可變,并帶有可選的圓括號。

元組是:

  • 不可變
  • 有序
  • 異質(zhì)
  • 索引(從零開始)
  • 帶圓括號(可選,但建議)
  • 在迭代過程中更快,因?yàn)樗遣豢勺兊?/li>

元組對于創(chuàng)建通常包含相關(guān)信息(例如員工信息)的對象很有用。換句話說,元組可以讓我們將相關(guān)信息“塊”在一起,并將其用作單個事物。

1. Creating a Tuple

元組中的元素用圓括號括起來,并用逗號分隔。元組可以包含任意數(shù)量的不同類型的項。

句法

Tuple = (item1, item2, item3)

元組的例子

tuple1 = () # empty tuple

tuple2 = (1, "2", 3.0)

tuple3 = 1, "2", 3.0

1.1. Tuple with one element

如果元組僅包含一個元素,則不將其視為元組。它應(yīng)該以逗號結(jié)尾以指定解釋器為元組。

元組的例子

tupleWithOneElement = ("hello", ) # Notice trailing comma

1.2. Nested Tuple

一個包含另一個元組作為元素的元組,稱為嵌套元組。

嵌套元組

nestedTuple = ("hello", ("python", "world"))

2. Accessing Tuple Items

我們可以使用方括號內(nèi)的索引訪問元組項。

  • 正索引從元組的開始開始計數(shù)。
  • 負(fù)索引從元組的末尾開始計數(shù)。
  • 一定范圍的索引將使用指定的項目創(chuàng)建一個新的元組(稱為Slicing)。
  • 范圍[m:n]是指從位置m()到位置n(不含)。
  • 使用雙索引訪問嵌套元組的元素。

存取項目

Tuple = ("a", "b", "c", "d", "e", "f")

print(Tuple[0]) # a

print(Tuple[1]) # b

print(Tuple[-1]) # f

print(Tuple[-2]) # e

print(Tuple[0:3]) # ('a', 'b', 'c')

print(Tuple[-3:-1]) # ('d', 'e')

Tuple = ("a", "b", "c", ("d", "e", "f"))

print(Tuple[3]) # ('d', 'e', 'f')

print(Tuple[3][0]) # d

print(Tuple[3][0:2]) # ('d', 'e')

3. Loop into tuple

使用for循環(huán)遍歷元組項。

對于循環(huán)示例

Tuple = ("a", "b", "c")

for x in Tuple:

print(x)

4. Check if an item exist in tuple

要檢查一個元組是否包含給定的元素,我們可以使用'in'關(guān)鍵詞和'not in'關(guān)鍵詞。

檢查項目是否存在于元組中

Tuple = ("a", "b", "c", "d", "e", "f")

if "a" in Tuple:

print("Yes, 'a' is present") # Yes, 'a' is present

if "p" not in Tuple:

print("No, 'p' is not present") # No, 'p' is not present

5. Sorting a Tuple

使用語言內(nèi)置sorted()方法對元組內(nèi)的元素進(jìn)行排序。

排序元組

Tuple = ("a", "c", "b", "d", "f", "e")

sortedTuple = sorted(Tuple)

print (sortedTuple) # ("a", "b", "c", "d", "e", "f")

6. Repetition and Concatenation of Tuples

要重復(fù)元組的所有元素,請將其乘以所需因子N。

重復(fù)

Tuple = ("a", "b")

repeatedTuple = Tuple * 3

print (repeatedTuple) # ('a', 'b', 'a', 'b', 'a', 'b')

要連接/連接兩個或多個元組,我們可以使用+運(yùn)算符。

級聯(lián)

Tuple1 = ("a", "b", "c")

Tuple2 = ("d", "e", "f")

joinedTuple = Tuple1 + Tuple2

print (joinedTuple) # ("a", "b", "c", "d", "e", "f")

7. Packing and Unpacking the Tuple

打包 是指我們?yōu)樽兞糠峙湟唤M值的操作。在打包時,元組中的所有項目都分配給一個元組對象。

在下面的示例中,所有三個值都分配給了variable Tuple。

Packing

Tuple = ("a", "b", "c")

拆包 稱為將元組變量分配給另一個元組,并將元組中的各個項目分配給各個變量的操作。

在給定的示例中,元組被解包為新的元組,并且將值"a", "b" and "c"–分配給了變量x, y and z

Unpacking

Tuple = ("a", "b", "c") # Packing

(x, y, z) = Tuple

print (x) # a

print (y) # b

print (z) # c

在解包期間,分配左側(cè)的元組中的元素數(shù)必須等于右側(cè)的數(shù)量。

Unpacking errors

Tuple = ("a", "b", "c") # Packing

(x, y, z) = Tuple       # ValueError: too many values to unpack (expected 2)

(x, y, z, i) =  Tuple   # ValueError: not enough values to unpack (expected 4, got 3)

8. Named tuples

Python提供了一種來自模塊的特殊類型的函數(shù),名為namedtuple()collection。

命名元組類似于字典,但是支持從值和鍵進(jìn)行訪問,其中字典僅支持按鍵訪問。

命名元組示例

import collections

Record = collections.namedtuple('Record', ['id', 'name', 'date'])

R1 = Record('1', 'My Record', '12/12/2020')

#Accessing using index

print("Record id is:", R1[0]) # Record id is: 1

# Accessing using key  

print("Record name is:", R1.name) # Record name is: My Record

9. Python Tuples Methods

9.1. any()

返回True如果至少一個元素存在于元組,并返回False如果元組是空的。

print( any( () ) ) # Empty tuple - False

print( any( (1,) ) ) # One element tuple - True

print( any( (1, 2) ) ) # Regular tuple - True

9.2. min()

返回元組的最小元素(整數(shù))。

Tuple = (4, 1, 2, 6, 9)

print( min( Tuple ) ) # 1

9.3. max()

返回元組的最大元素(整數(shù))。

Tuple = (4, 1, 2, 6, 9)

print( max( Tuple ) ) # 9

9.4. len()

返回元組的長度。

Tuple = (4, 1, 2, 6, 9)

print( len( Tuple ) ) # 5

9.5. sum()

返回元組的所有元素(整數(shù))的總和。

Tuple = (4, 1, 2, 6, 9)

print( sum( Tuple ) ) # 22

10. Conclusion

如上所述,元組不可變,有序和索引的異構(gòu)元素集合。它寫有或沒有圓括號。

元組對于創(chuàng)建對象類型和實(shí)例非常有用。

元組支持類似于list類型的操作,只有我們不能更改元組元素。

學(xué)習(xí)愉快!

作者:分布式編程
出處:https://zthinker.com/
如果你喜歡本文,請長按二維碼,關(guān)注 分布式編程
.

分布式編程

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容