关于列表的函数
元组-tuple
元组创建
t = ( )
print ( type ( t) )
t = ( 1 , )
print ( type ( t) )
print ( t)
t = 1 ,
print ( type ( t) )
print ( t)
t = ( 1 , 2 , 3 , 4 , 5 )
print ( type ( t) )
print ( t)
t = 1 , 2 , 3 , 4 , 5
print ( type ( t) )
print ( t)
l = [ 1 , 2 , 3 , 4 , 5 ]
t = tuple ( l)
print ( type ( t) )
print ( t)
<class 'tuple'>
<class 'tuple'>
(1,)
<class 'tuple'>
(1,)
<class 'tuple'>
(1, 2, 3, 4, 5)
<class 'tuple'>
(1, 2, 3, 4, 5)
<class 'tuple'>
(1, 2, 3, 4, 5)
元组的特性
是序列表,有序 元组数据值可以访问,不能修改,不能修改,不能修改 元组数据可以是任意类型 总之,list所有特性,除了可修改外,元组都具有 也就意味着,list具有的一些操作,比如索引,分片,序列相加,相乘,成员资格操作等,一模一样
t = ( 1 , 2 , 3 , 4 , 5 )
print ( t[ 4 ] )
5
print ( t[ 12 ] )
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-34-47f420862c37> in <module>()
----> 1 print(t[12])
IndexError: tuple index out of range
t = ( 1 , 2 , 3 , 4 , 5 , 6 )
t1 = t[ 1 : : 2 ]
print ( id ( t) )
print ( id ( t1) )
print ( t1)
t2 = t[ 2 : 100 ]
print ( t2)
140249409775272
140249408604272
(2, 4, 6)
(3, 4, 5, 6)
t1 = ( 1 , 2 , 3 )
t2 = ( 5 , 6 , 7 )
print ( t1)
print ( id ( t1) )
t1 = t1 + t2
print ( t1)
print ( id ( t1) )
t1 = ( 1 , 2 , 3 )
t1 = ( 2 , 3 , 4 )
t1[ 1 ] = 100
(1, 2, 3)
140249408457464
(1, 2, 3, 5, 6, 7)
140249409775368
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-46-42380d3cdd39> in <module>()
16 # tuple 的不可修改,指的是内容的不可修改
17 # 修改tuple内容会导致报错
---> 18 t1[1] = 100
TypeError: 'tuple' object does not support item assignment
t = ( 1 , 2 , 3 )
t = t * 3
print ( t)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
t = ( 1 , 2 , 3 )
if 2 in t:
print ( "YES" )
else :
print ( "NO" )
YES
t = ( 1 , 2 , 3 , "wangxiaojing" , "i" , "love" )
for i in t:
print ( i, end= " " )
1 2 3 wangxiaojing i love
t = ( ( 1 , 2 , 3 ) , ( 2 , 3 , 4 ) , ( "i" , "love" , "wangxiaojing" ) )
for i in t:
print ( i)
for k, m, n in t:
print ( k, '--' , m, '--' , n)
(1, 2, 3)
(2, 3, 4)
('i', 'love', 'wangxiaojing')
1 -- 2 -- 3
2 -- 3 -- 4
i -- love -- wangxiaojing
关于元组的函数
t = ( 1 , 2 , 3 , 4 , 5 )
len ( t)
5
print ( max ( t) )
print ( min ( t) )
5
1
l = [ 1 , 2 , 3 , 4 , 5 ]
t = tuple ( l)
print ( t)
t = tuple ( )
print ( t)
(1, 2, 3, 4, 5)
()
元组的函数
t = ( 2 , 1 , 2 , 3 , 45 , 1 , 1 , 2 , )
print ( t. count( 2 ) )
print ( t. index( 45 ) )
print ( t. index( 1 ) )
3
4
1
元组变量交换法
a = 1
b = 3
print ( a)
print ( b)
print ( "*" * 20 )
c = a
a = b
b = c
print ( a)
print ( b)
print ( "*" * 20 )
a, b = b, a
print ( a)
print ( b)
1
3
********************
3
1
********************
1
3