元祖和字符串一样是不可改变的,元组用于接收函数返回值

  • 元祖定义
1
2
3
4
5
6
7
#定义单元素元祖
t1 = (1,)
t2 = (1)
#t2为字符串,注意区别

#元祖内可包含字符串,数字,列表,元祖
t3 = (1,2,'sdf',['asf'],(1,))
  • 元祖的操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#元祖拆分,用于函数返回值
In [18]: a = 'abcdef'

In [19]: t = (a,'b','c')

In [20]: t
Out[20]: ('abcdef', 'b', 'c')

In [21]: first,second,third = t

In [22]: first
Out[22]: 'abcdef'

In [23]: second
Out[23]: 'b'

In [24]: third
Out[24]: 'c'

#计算元组内元素个数
In [28]: t
Out[28]: ('abcdef', 'b', 'c')

In [29]: t.count('b')
Out[29]: 1

In [30]: t.count('bb')
Out[30]: 0

#查看元素的索引
In [36]: t = (a,'b','c','b','z','b')

In [37]: t.index('b')
Out[37]: 1

In [38]: t.index('b',3)
Out[38]: 3

In [39]: t.index('b',4)
Out[39]: 5

In [40]: t.index('b',4,9)
Out[40]: 5