Python之元组类型(特性、常用方法等等)

一、元组的创建

元组(tuple): 
	元组本身是不可变数据类型,没有增删改查
	元组内可以存储任意数据类型

创建:

t = (1,2.3,'http',True)
print(t,type(t))

在这里插入图片描述
虽然元组没有增删改查,但是我们可以通过修改元组中的可变数据类型来间接修改元组内容。

示例:

t = ([1,2,3],4)
t[0].append(5)
print(t)

在这里插入图片描述
需要注意的是,如果元组只有一个元素时候,后面要加逗号,否则数据类型不确定

t = (1)
print(type(t))

t1 = (1,)
print(type(t1))

在这里插入图片描述

二、元组的特性

1、索引、切片

Allowuses = ('root','redhat','ftp')
Allowpasswd = ('123','456','789')

#索引
print(Allowuses[0])
print(Allowpasswd[-1])

#切片
print(Allowuses[1:])
print(Allowuses[:-1])
print(Allowuses[::-1])

在这里插入图片描述

2、重复

Allowuses = ('root','redhat','ftp')
Allowpasswd = ('123','456','789')

print(Allowuses * 2)

在这里插入图片描述

3、连接

Allowuses = ('root','redhat','ftp')
Allowpasswd = ('123','456','789')

print(Allowuses + ('linux','samba'))

在这里插入图片描述

4、成员操作符

Allowuses = ('root','redhat','ftp')
Allowpasswd = ('123','456','789')

print('ssh' in Allowuses)
print('ssh' not in Allowuses)

在这里插入图片描述

5、for循环(迭代)

Allowusers = ('root','redhat','ftp')
Allowpasswd = ('123','456','789')

for user in Allowusers:
    print(user)
for index,user in enumerate(Allowusers):
    print('%d :%s '%(index+1,user))

for user,passwd in zip(Allowusers,Allowpasswd):
    print(user,':',passwd)

在这里插入图片描述

三、元组的常用方法

t = (1,2.3,True,'linux')

print(t.count('linux'))		#统计linux字符串出现的次数
print(t.index(1))			#打印出1这个元素在元组中的索引值

在这里插入图片描述

四、元组的应用场景

#元组的赋值,有多少个元素,就用多少个变量接收

t = ('westos',11,100)
name,age,score = t
print(name,age,score)

在这里插入图片描述
类型之间的转换:

t = (100,78,89,32,23)
lt = list(t)		#将元组转化为列表
print(lt)
lt.sort()
print(lt)

在这里插入图片描述

t = (100,78,89,32,23)
lt = list(t)
print(lt)
lt = sorted(lt)
print(lt)

在这里插入图片描述

t = (100,78,89,32,23)
lt = list(t)
print(lt)
lt = sorted(lt)
print(lt)
minscore,*middlescore,maxscore = lt
print(minscore)
print(middlescore)
print(maxscore)

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值