首页 > 其他 > 详细

组合数据类型(元组)

时间:2019-03-24 16:05:10      阅读:153      评论:0      收藏:0      [点我收藏+]

1,创建元组

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);               # 可以是任基本数据类型构成
tup2 = (1, 2, 3, 4, 5 );                # 纯数字
tup3 = "a", "b", "c", "d"               # 可以不加括号
tup4 = (50,)                            # 元组中只包含一个元素时,需要在元素后面添加逗号

2,基本操作

a,连接

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);
tup2 = (1,2,3,4)
print (tup1+tup2)
>>>(‘physics‘, ‘chemistry‘, 1997, 2000, 1, 2, 3, 4)

  b,判断

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);
a = ‘physics‘
print (a in tup1)
>>>True

  c,复制

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);
print (tup1*2)
>>>(‘physics‘, ‘chemistry‘, 1997, 2000, ‘physics‘, ‘chemistry‘, 1997, 2000)

d,索引

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);
print (tup1[0], tup2[2])
>>>‘physics‘
1997

  b,切片

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);
print (tup1[0:2])
>>>(‘physics‘, ‘chemistry‘)

  e,步长

tup1 = ("physics","chemistry",1997,2000,1800,"english");
print (tup1[0:4:2])                  # 0代表索引起始值,4代表索引结束值,2为步长
print (tup1[::2])                    # 以2为步长,截取整个列表
print (tup1[1::2])                   # 1为索此起始值,2为步长截取整个列表
>>>(‘physics‘, 1997)
(‘physics‘, 1997, 1800)
(‘chemistry‘, 2000, ‘english‘)

3,常用功能

a,统计个数

tup1 = ("physics","chemistry",1997,2000,1800,"english");
a = len(tup1)                        # 计算元组内元素个数             
print (a)
>>>6

  b,最大值

tup1 = ("physics","english","chemistry");
print (max(tup1))             # 使用该函数时,元组内元素必须统一数据类型      
>>>physics

  c,最小值

tup1 = ("physics","english","chemistry");
print (min(tup1))               # 使用该函数时,元组内数据类型必须统一
>>>chemistry

  d,数据转换

tup1 = ["physics","english","chemistry"]
print (tup1)
print (tuple(tup1))
>>>[‘physics‘, ‘english‘, ‘chemistry‘]               # 此数据类型为列表
(‘physics‘, ‘english‘, ‘chemistry‘)                       # 此数据类型为元组

  

组合数据类型(元组)

原文:https://www.cnblogs.com/qianqicheng/p/10541416.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!