一、简述
- 元组(tuple)的用法和list基本一样,但是,元组不能删除修改,这是元组最关键的特性
- 元组可以做为字典的key
>>> tup1=(1,2,3)
>>> tup2=(4,5,6)
>>> dict2={tup1:1,tup2:2}
>>> dict2
{(1, 2, 3): 1, (4, 5, 6): 2}
二、常用方法和属性
1.定义元组
arr = () #空元组
arr=("123","456","789")
2.获取第一个元素
arr=("123","456","789")
print(arr[0]);
结果:123
3.遍历(迭代)
arr=("123","456","789")
for a in arr:
print(a);
结果:123
456
789
4.count()方法--统计指定元素在元组中出现的次数
arr=("123","456","123")
count=arr.count("123")
print(count);
结果:2
5.index():统计字符串在元组中第一次出现的位置
arr=("123","456","123")
count=arr.index("123")
print(count);
结果:0
6.元组解包
arr=("123","456","123")
a,b,c = arr
结果:a = "123", b = "456", c="123"
7.测试删除元组中的数据
arr=("123","456","123")
del arr[0:1]
print(arr);
结果:TypeError: 'tuple' object does not support item deletion