python元祖基本操作


#-*- coding:utf-8 -*-
# 創建空元組
# temp1 = ();
# 如果元祖中只包含一個值,需用逗號隔開消除歧義
# temp1=(1,)

# 元祖的基本操作
# 訪問元祖,可以使用下標索引訪問元素的值
# temp1=('hello','world')
# print temp1[1]
# world
# temp1=(1,2,3,5,7,6)
# print temp1[1:5]

#修改元祖
# 元祖中的元素值不允許修改,但可以對元祖進行連接組合
# temp1=('hello','world')
# num =(2018,2)
# print temp1+num
# ('hello', 'world', 2018, 2)

# 刪除元祖
# 元祖中的元素不允許刪除,但可以使用del語句刪除整個元祖
# temp=('hello','world')
# del temp
# print temp
# Traceback (most recent call last):
# File "C:/Users/Administrator/PycharmProjects/untitled1/Class2String/vacation.py", line 26, in <module>
# print temp
# NameError: name 'temp' is not defined
# 此時元祖已被刪除,輸出變量會有異常

# 元祖的索引,截取
# temp1=('hello','world','welcome')
# print temp1[2]
# welcome
# print temp1[-2]
# world
# print temp1[1:]
# ('world', 'welcome')

# 元祖的內置函數
# tup=('hello','world','welcome')
# print len(tup) 用於計算元祖元素個數
# 3
# tup =(2,7,2,9,4)
# print max(tup) 用於求最大值
# 9
# print min(tup) 用於求最小值
# 2

# tuple(seq) 用於將列表轉換為元祖
# tupl=['hello','world','welcome']
# tup=tuple(tupl)
# print tup
# ('hello', 'world', 'welcome')


免責聲明!

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



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