元组

2020-09-09  本文已影响0人  小圆圈Belen

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

tuple = ('hi', 1, '你好')
print(tuple)

结果:
('hi', 1, '你好')
访问元组

元组的访问和列表的访问方式一样
例子:

tuple = ('hi', 1, '你好')
print(tuple[2])

结果:
你好
修改元组

python中不允许修改元组的数据
例子:

tuple = ('hi', 1, '你好')
tuple[0] = 'hello'
print(tuple)
结果:
Traceback (most recent call last):
  File "tuple.py", line 6, in <module>
    tuple[0] = 'hello'
TypeError: 'tuple' object does not support item assignment
删除元组

python中不允许删除元组的数据
例子:

tuple = ('hi', 1, '你好')
del tuple[1]
print(tuple)
结果:
Traceback (most recent call last):
  File "tuple.py", line 10, in <module>
    del tuple[1]
TypeError: 'tuple' object doesn't support item deletion
查找元组(index、count)
 a = ('a', 'b', 'c', 'a', 'b')
a.index('a', 1, 3) 

结果:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list
 a = ('a', 'b', 'c', 'a', 'b')
a.count('b') 

结果:
2
#不存在的话返回0
上一篇 下一篇

猜你喜欢

热点阅读