Python学习笔记-元组

元组

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号

<1>访问元组

name = ('Emma', 'May', 'Abby')
print(name[0],name[2])

运行结果

Emma Abby

<2>修改元组

name[2] = 'Kelly'

运行结果

Traceback (most recent call last):
  File "E:/PycharmProjects/train/tupletest.py", line 17, in <module>
    name[2] = 'Kelly'
TypeError: 'tuple' object does not support item assignment

说明: python中不允许修改元组的数据,包括不能删除其中的元素

<3>元组的内置函数count, index

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

a = ('a', 'b', 'c', 'a', 'b')
a.index('a', 1, 3) # 注意是左闭右开区间
print(a.index('a', 1, 4))
print(a.count('b'))
print(a.count('d'))

运行结果

Traceback (most recent call last):
  File "E:/PycharmProjects/train/tupletest.py", line 21, in <module>
    a.index('a', 1, 3) # 注意是左闭右开区间
ValueError: tuple.index(x): x not in tuple
3
2
0
原文地址:https://www.cnblogs.com/Akubi/p/9354730.html