元祖 tuple

  元组其实跟列表类似,也是存一组数,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。只不过它一旦创建,便不能再修改,所以又叫只读列表

【1】创建元祖

>>> aTuple = ('python',1,2)
>>> aTuple
('python',1,2)

【2】访问元祖

aTuple = ('a','b','c')
>>> aTuple[0]
'a'
>>> aTuple[2]
'c'
>>>

【3】修改元祖

  python中不允许修改元祖的数据,包括不能删除其中的元素,但是可以对元祖进行连接组合

>>> aTuple = ('a','b','c')
>>> aTuple[1] = 'd'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> aTuple = ('a','b','c')
>>> bTuple = ('c','d','e')
>>> cTuple = aTuple + bTuple
>>> cTuple
('a', 'b', 'c', 'c', 'd', 'e')

【4】删除元祖

  元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组。元组被删除后,输出变量会有异常信息

>>> aTuple = ('a','b','c')
>>> del aTuple
>>> aTuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'aTuple' is not defined

【5】元祖运算符

  与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。

Python 表达式结果描述
len((1, 2, 3))3计算元素个数
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)连接
('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')复制
3 in (1, 2, 3)True元素是否存在
for x in (1, 2, 3): print x,1 2 3迭代

 

【6】元祖索引,截取

  因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素。

  L = ('Google', 'Taobao', 'Runoob')
Python 表达式结果描述
L[2]'Runoob'读取第三个元素
L[-2]'Taobao'反向读取;读取倒数第二个元素
L[1:]('Taobao', 'Runoob')截取元素,从第二个开始后的所有元素。
>>> L = ('Google', 'Taobao', 'Runoob')
>>> L[2]
'Runoob'
>>> L[-2]
'Taobao'
>>> L[1:]
('Taobao', 'Runoob')

【7】元祖内置函数

  index和count与字符串和列表中的用法相同

>>> aTuple = ('a', 'b', 'c', 'a', 'b')
>>> aTuple.index('a',1,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
>>> aTuple.index('a',1,4)
3
>>> aTuple.count('b')
2
>>> aTuple.count('d')
0
序号方法及描述实例
1len(tuple)
计算元组元素个数。
>>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 >>>
2max(tuple)
返回元组中元素最大值。
>>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' >>>
3min(tuple)
返回元组中元素最小值。
>>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' >>>
4tuple(seq)
将列表转换为元组。
>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu')


 

转载于:https://www.cnblogs.com/Jiangchuanwei/p/8486722.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值