######元组######
1.为什么需要元组?
比如:打印用户的姓名
In [1]: user1 = “juff 8 male”
In [2]: user1[0:4]
Out[2]: ‘juff’
结论:字符串中操作提取姓名/年龄/性别的方式不方便,诞生元组.
2.元组的定义
•- 定义空元组 tuple = ()
•- 定义单个值的元组 tuple = (fentiao,)
•- 一般的元组 tuple = (fentiao, 8, male)
In [3]: tuple = ()
In [6]: tuple = (“baidu”,)
In [7]: tuple = (“baidu”,”18”,”male”)
3.元组特性
• 不能对元组的值任意更改;
In [8]: tuple[0] = (“haha”)
TypeError Traceback (most recent call last)
in ()
—-> 1 tuple[0] = (“haha”)
TypeError: ‘tuple’ object does not support item assignment
• 对元组分别赋值,引申对多个变量也可通过元组方式分别赋值
In [10]: name,age,gender = tuple
In [11]: print name,age,gender
baidu 18 male
• 可以更改元组内列表的值
In [13]: t1 = ([‘172.25.254.108’,’172.25.0.250’],’server8.example.com’)
In [14]: t1[0][0] = ‘172.25.254.8’
In [15]: print t1
([‘172.25.254.8’, ‘172.25.0.250’], ‘server8.example.com’)
4.元组的操作
元组也属于序列,可执行的操作如:索引、切片、重复、连接和查看长度
In [16]: t2 = (‘1’,’2’,’3’)*3
In [17]: print t2
(‘1’, ‘2’, ‘3’, ‘1’, ‘2’, ‘3’, ‘1’, ‘2’, ‘3’)
In [18]: t3 = (‘hi’,’tom’)
In [19]: t4 = (‘how’,’are’,’you’)
In [20]: print t3 + t4
(‘hi’, ‘tom’, ‘how’, ‘are’, ‘you’)
In [21]: len(t3)
Out[21]: 2
In [22]: len(t4)
Out[22]: 3
删除元组
In [23]: t1
Out[23]: ([‘172.25.254.8’, ‘172.25.0.250’], ‘server8.example.com’)
In [24]: del(t1)
In [25]: t1
NameError Traceback (most recent call last)
in ()
—-> 1 t1
NameError: name ‘t1’ is not defined
5.元组的方法
• t.count(value)–>int 返回value在元组中出现的次数;
In [26]: t2
Out[26]: (‘1’, ‘2’, ‘3’, ‘1’, ‘2’, ‘3’, ‘1’, ‘2’, ‘3’)
In [27]: t2.count(“1”)
Out[27]: 3
• t.index(value) 返回value在元组中的偏移量(即索引值)