签到成功

知道了

CNDBA社区CNDBA社区

Python第9天-元组

2021-11-01 21:42 865 0 原创 Python
作者: hbhe0316

Python 中的数据结构是通过某种方式组织在一起的数据元素的集合,这些数据元素可以是数字、字符、甚至可以是其他数据结构 在 Python 中,最基本的数据结构是序列(列表和元组),序列中的每个元素都有一个序号(元素的具体位置),这个序号叫索引,索引下标从 0 开始。
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号(),列表使用方括号[]。

1.1.创建元组

http://www.cndba.cn/hbhe0316/article/5023

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 修改元组
元组中的值一旦定义就不能修改,但是我们可以通过元组与元组之间的连接关系来对元组进行修改,例如http://www.cndba.cn/hbhe0316/article/5023http://www.cndba.cn/hbhe0316/article/5023http://www.cndba.cn/hbhe0316/article/5023

tuple1 = ('beijing', 'shanghai', 1949, 2000);
tuple2 = (1, 2, 3, 4, 5 );
tuple3 = "a", "b", "c", "d","e";
tuple4 = ()
print(tuple1 + tuple2 + tuple3)

http://www.cndba.cn/hbhe0316/article/5023

1.4 删除元组
由于元组的不可修改性,所以元组中的元素值是不允许删除的,但我们可以使用 del 语句来删除整个元组,如下实例:http://www.cndba.cn/hbhe0316/article/5023

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 元组运算符
与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。总而言之对整个元组进行一些运算后就会生成一个新的元组。http://www.cndba.cn/hbhe0316/article/5023

2.1 元组求长度
元组求长度使用运算函数 len ,如下

tuple1 = ('beijing', 'shanghai', 1949, 2000);
print (len(tuple1))

http://www.cndba.cn/hbhe0316/article/5023

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 元组内置函数
和列表一样,元组同样也拥有一些内置函数,这些函数用于判元组中的元素大小以及将元组做相应的转换

http://www.cndba.cn/hbhe0316/article/5023

tuple1 = (1911, 1921, 1949, 2000);
print(len(tuple1))
print(max(tuple1))
print(min(tuple1))

http://www.cndba.cn/hbhe0316/article/5023

版权声明:本文为博主原创文章,未经博主允许不得转载。

python

用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
hbhe0316

hbhe0316

关注

1.只有承认无知,才能装下新的东西; 2.进步来自一点点滴滴的积累; 3.广博让你更优秀,而专业让你无法替代; 4.挫折和失败能够转换为一种财富。

  • 889
    原创
  • 1
    翻译
  • 13
    转载
  • 24
    评论
  • 访问:1040031次
  • 积分:1523
  • 等级:核心会员
  • 排名:第6名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ