分享

python:元组【全用法】

 乙甲壬 2020-07-11

python中有列表、元组、集合、字典这四种可以存放多个数据元素的集合,他们在总体功能上都起着存放数据的作用,却都有着各自的特点。本片文章中我们会对元组的用法做详细说明。

演示环境:

python3.6
pycharm中的python3.6

元组(tuple):存储任意类型数据,但其内数据不可变。元组不可变,其内的列表中的元素可以变

t = (1,2.3,True,'abc') ##元组内类型任意print(type(t))
  • 1
  • 2

在这里插入图片描述

t1 = ([1,2,3],4) ###可以修改其中列表的元素
t1[0].append(4)
print(t1)
在这里插入图片描述

第一部分:元组特性:

1.1:定义:

t2 = ()          ##空元组的定义print(type(t2))t2 = ('xyy',)   ##单个内容元祖定义 【不加逗号为字符串类型】print(type(t2))t2 = ('xyy')  ##为字符串类型print(type(t2))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述
下面内容将以该内容为基础:

users = ('root','westos','redhat')passwds = ('123','456','012')
  • 1
  • 2

1.2索引 切片:

print(users[0])print(users[:1])   #切出第一个元素
  • 1
  • 2

在这里插入图片描述
1.3重复

print(users * 3)
  • 1

在这里插入图片描述

1.4连接

print(passwds + ('012','230'))
  • 1

在这里插入图片描述
1.5成员操作符:

print('redhat' in users)print('redhat' not in users)
  • 1
  • 2

在这里插入图片描述

1.6迭代 ##循环遍历

for user in users:	print(user)
  • 1
  • 2

在这里插入图片描述

枚举 + 迭代: ##循环遍历并返回索引值和value

for index,user in enumerate(users): print('第%d个用户:%s' %(index+1,user))
  • 1
  • 2

枚举 + 压缩: ##先对应压缩在一起,再枚举遍历输出

for user,passwd in zip(users,passwds):   	print(user,':',passwd)
  • 1
  • 2

在这里插入图片描述


第二部分:元组常用方法:

2.1计数:

t = (1,2.3,True,'westos')print(t.count('westos')) ##统计出现次数print(t.index(1)) ##统计最小索引值
  • 1
  • 2
  • 3

在这里插入图片描述

2.2排序:

a.sort()   ###方法   ##元组不能方法排序sorted(a)  ###函数
  • 1
  • 2

在这里插入图片描述

2.3接收多个参数

scores = (65,89,59,78,100)minscore,*middlescore,maxscore = scores ##将第一个参数赋值给minscore,最后一个参数赋值给maxscore,其余参数所有赋给middlescoreprint(minscore)print(middlescore)print(maxscore)
  • 1
  • 2
  • 3
  • 4
  • 5

在这里插入图片描述


大大的小小阳

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多