Tuple
什么是Tuple?
Tuple是python对象组成的序列,此序列内容不可变,即不能编辑元素,这一点和List不同; 定义Tuple使用逗号将对象分割,或者将分割的对象放在括号内;
tup1 = ( "physics" , "chemistry" , 1997 , 2000 )
tup2 = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 )
tup3 = "a" , "b" , "c" , "d"
tup1 = ( )
print ( type ( tup1) )
print ( tup1)
tup1 = ( 50 , )
与索引一样,tuple索引从0开始,可以切断,级联等
如何获取Tuple的值?
tup1 = ( 'physics' , 'chemistry' , 1997 , 2000 )
tup2 = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 )
print ( "tup1[0]: " , tup1[ 0 ] )
print ( "tup2[1:5]: " , tup2[ 1 : 5 ] )
更新Tuple
Tuple是不可变的,意味着tuple内对象的值不能更新或修改,但是可以通过获取tuple部分对象创建新的tuple
tup1 = ( 12 , 34.56 ) ;
tup2 = ( 'abc' , 'xyz' ) ;
tup3 = tup1 + tup2;
print ( tup3)
( 12 , 34.56 , 'abc' , 'xyz' )
删除Tuple元素
删除tuple单个元素是不可能的,只能用del语句删除整个tuple
tup = ( 'physics' , 'chemistry' , 1997 , 2000 ) ;
print ( tup)
del tup
print "After deleting tup : " ;
print ( tup)
NameError: name 'tup' is not defined
Tuple的基本操作符
与字符串类似,tuple响应+,*的操作符,表示结合,重复;不同的是结果是新的tuple 事实上,tuple响应以下所有的操作
Python Expression Result Description len((1,2,3)) 3 length (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation (‘Hi!’,) * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) Repetition 3 in (1, 2, 3) True Membership for x in (1, 2, 3): print x 1 2 3 Iteration
索引切片矩阵
因为tuple是序列,因此适用于string的索引,切片,矩阵一样适用于tuple
L = ( 'spam' , 'Spam' , 'SPAM!' )
Python Expression Result Description L[2] ‘SPAM!’ Offsets start at zero L[-2] ‘Spam’ Negative: count from the right L[1:] (‘Spam’, ‘SPAM!’) Slicing fetches sections
无封闭分隔符
任何一组以逗号分隔的的多个对象,写入时不带标识符号,即List不带[],tuple不带(),都默认为tuple
print ( 'abc' , - 4.24e93 , 18 + 6.6j , 'xyz' )
x, y = 1 , 2
print ( "Value of x , y : " , x, y)
abc - 4.24e+93 ( 18 + 6.6j ) xyz
Value of x , y : 1 2
Tuple的内联方法
Sr.No. Function with Description 1 cmp(tuple1, tuple2) Compares elements of both tuples. 2 len(tuple) Gives the total length of the tuple 3 max(tuple) Returns item from the tuple with max value. 4 min(tuple) Returns item from the tuple with min value. 5 tuple(seq) Converts a list into tuple.