亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python入門教程(十三)Python元組

 更新時間:2023年04月14日 11:13:12   作者:輕松學Python  
這篇文章主要介紹了Python入門教程(十三)Python元組,Python是一門非常強大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下

元組(Tuple)

元組是有序且不可更改的集合。在 Python 中,元組是用圓括號編寫的。

實例

創(chuàng)建元組:

thistuple = ("apple", "banana", "cherry")
print(thistuple)

運行實例

訪問元組項目

您可以通過引用方括號內(nèi)的索引號來訪問元組項目:

實例

打印元組中的第二個項目:

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

運行實例

負索引

負索引表示從末尾開始,-1 表示最后一個項目,-2 表示倒數(shù)第二個項目,依此類推。

實例

打印元組的最后一個項目:

thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

運行實例

索引范圍

您可以通過指定范圍的起點和終點來指定索引范圍。

指定范圍后,返回值將是帶有指定項目的新元組。

實例

返回第三、第四、第五個項目:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

運行實例

注釋:搜索將從索引 2(包括)開始,到索引 5(不包括)結(jié)束。

請記住,第一項的索引為 0。

負索引范圍

如果要從元組的末尾開始搜索,請指定負索引:

實例

此例將返回從索引 -4(包括)到索引 -1(排除)的項目:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

運行實例

更改元組值

創(chuàng)建元組后,您將無法更改其值。元組是不可變的,或者也稱為恒定的。

但是有一種解決方法。您可以將元組轉(zhuǎn)換為列表,更改列表,然后將列表轉(zhuǎn)換回元組。

實例

把元組轉(zhuǎn)換為列表即可進行更改:

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

運行實例

遍歷元組

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

實例

遍歷項目并打印值:

thistuple = ("apple", "banana", "cherry")
for x in thistuple:
  print(x)

運行實例

我們將在 Python For 循環(huán) 這一章中學習有關(guān) for 循環(huán)的更多知識。

檢查項目是否存在

要確定元組中是否存在指定的項,請使用 in 關(guān)鍵字:

實例

檢查元組中是否存在 “apple”:

thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
  print("Yes, 'apple' is in the fruits tuple")

運行實例

元組長度

要確定元組有多少項,請使用 len() 方法:

實例

打印元組中的項目數(shù)量:

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

運行實例

添加項目

元組一旦創(chuàng)建,您就無法向其添加項目。元組是不可改變的。

實例

您無法向元組添加項目:

thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" 
# 會引發(fā)錯誤
print(thistuple)

運行實例

創(chuàng)建有一個項目的元組

如需創(chuàng)建僅包含一個項目的元組,您必須在該項目后添加一個逗號,否則 Python 無法將變量識別為元組。

實例

單項元組,別忘了逗號:

thistuple = ("apple",)
print(type(thistuple))

#不是元組
thistuple = ("apple")
print(type(thistuple))

運行實例

刪除項目

注釋:您無法刪除元組中的項目。

元組是不可更改的,因此您無法從中刪除項目,但您可以完全刪除元組:

實例

del 關(guān)鍵字可以完全刪除元組:

thistuple = ("apple", "banana", "cherry")
del thistuple

print(thistuple) # 這會引發(fā)錯誤,因為元組已不存在。

運行實例

合并兩個元組

如需連接兩個或多個元組,您可以使用 + 運算符:

實例

合并這個元組:

tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2
print(tuple3)

運行實例

tuple() 構(gòu)造函數(shù)

也可以使用 tuple() 構(gòu)造函數(shù)來創(chuàng)建元組。

實例

使用 tuple() 方法來創(chuàng)建元組:

thistuple = tuple(("apple", "banana", "cherry")) # 請注意雙括號
print(thistuple)

運行實例

元組方法

Python 提供兩個可以在元組上使用的內(nèi)建方法。

到此這篇關(guān)于Python入門教程(十三)Python元組的文章就介紹到這了,更多相關(guān)Python元組內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論