Python 中的数据结构是通过某种方式组织在一起的数据元素的集合,这些数据元素可以是数字、字符、甚至可以是其他数据结构 在 Python 中,最基本的数据结构是序列(列表和元组),序列中的每个元素都有一个序号(元素的具体位置),这个序号叫索引,索引下标从 0 开始。
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号(),列表使用方括号[]。
1.1.创建元组
tuple1 = ('beijing', 'shanghai', 1949, 2000);
tuple2 = (1, 2, 3, 4, 5 );
tuple3 = "a", "b", "c", "d","e";
tuple4 = ()
1.2.访问元组
tuple1 = ('beijing', 'shanghai', 1949, 2000);
tuple2 = (1, 2, 3, 4, 5 );
tuple3 = "a", "b", "c", "d","e";
tuple4 = ()
print(type(tuple4))
print(tuple1)
print(tuple1[0:2])
1.3 修改元组
元组中的值一旦定义就不能修改,但是我们可以通过元组与元组之间的连接关系来对元组进行修改,例如
tuple1 = ('beijing', 'shanghai', 1949, 2000);
tuple2 = (1, 2, 3, 4, 5 );
tuple3 = "a", "b", "c", "d","e";
tuple4 = ()
print(tuple1 + tuple2 + tuple3)
1.4 删除元组
由于元组的不可修改性,所以元组中的元素值是不允许删除的,但我们可以使用 del 语句来删除整个元组,如下实例:
tuple1 = ('beijing', 'shanghai', 1949, 2000);
print (tuple1)
del tuple1;
print ("删除后的元组 tuple1 : ")
print (tuple1)
2.4 判断元素
判断元组中元素是否存在使用关键字 in 进行判断,判断结果返回布尔值
tuple1 = ('beijing', 'shanghai', 1949, 2000);
print('beijing' in tuple1)
2 元组运算符
与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。总而言之对整个元组进行一些运算后就会生成一个新的元组。
2.1 元组求长度
元组求长度使用运算函数 len ,如下
tuple1 = ('beijing', 'shanghai', 1949, 2000);
print (len(tuple1))
2.2 连接元组
两个甚至对个元组的连接使用 + 连接符,例如:
tuple1 = ('beijing', 'shanghai', 1949, 2000);
tuple2 = (1, 2, 3, 4, 5 );
tuple3 = "a", "b", "c", "d","e";
print (tuple1 + tuple2 + tuple3)
2.3 复制元组
tuple1 = ('beijing', 'shanghai', 1949, 2000);
print(tuple1 * 3)
2.4 判断元素
判断元组中元素是否存在使用关键字 in 进行判断,判断结果返回布尔值
2.5 元组中指定位置元素访问
和序列一样,元组中的元素同样可以使用索引号访问指定位置的元素,例如
tuple1 = ('beijing', 'shanghai', 1949, 2000);
print(tuple1[0:2])
print(tuple1[-1])
print(tuple1[-2])
3 元组内置函数
和列表一样,元组同样也拥有一些内置函数,这些函数用于判元组中的元素大小以及将元组做相应的转换
tuple1 = (1911, 1921, 1949, 2000);
print(len(tuple1))
print(max(tuple1))
print(min(tuple1))
版权声明:本文为博主原创文章,未经博主允许不得转载。
python
- 上一篇:Centos 7.9下安装kibana
- 下一篇:ORA-00054: 资源正忙