python元組(tuple)循環遍歷實例分析


一 概念:

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

 

二 使用方法:

1  基本創建:

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

 

2 訪問:

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

 

三 遍歷方法:

  1 基本方法:

thetuple=(1,3,5,7,9)

#first method
print("first method:")
for item in thetuple:
    print(item)

#second method
print("second method:")
for value in iter(thetuple):
    print(value)

 2 高級方法:

thetuple=(1,3,5,7,9)

#method one
print("first method:")
for index in range(len(thetuple)):
    print("index:",index, "value:",thetuple[index])


#method two
print("second method:")
for index,value in enumerate(thetuple):
    print("index:",index, "value:",value)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM