【Python】元组

前言

Python 元组
元组方法
元组操作
count
index
创建
访问
增加
删除
遍历
成员资格
运算符
长度
最值
排序

1. 元组方法

1.1 count

tuple.count(value):返回某个值在元组中出现的次数

tuple1 = (1,1,1,2,2,3)
print(tuple1.count(1)) # 3
print(tuple1.count(2)) # 2
print(tuple1.count(3)) # 1

# 元素值不在元组中也没关系
print(tuple1.count(4)) # 0

1.2 index

tuple.index(value[,start[,stop]]):返回某个值在元组中第一个匹配项的索引,如果该值不存在,则会引起错误

  • value:查找的值
  • start:可选,查找的起始位置(包含)
  • end:可选,查找的结束位置(不包含)
tuple1 = (1,2,3,2,1,4,3,3,4,1,1,2)
print(tuple1.index(1)) # 0
print(tuple1.index(2)) # 1
print(tuple1.index(3)) # 2

# 指定查找范围
print(tuple1.index(1,4)) # 4,从位置4开始(包含)查找值1
print(tuple1.index(1,5,10)) # 9,查找位置5(包含)到位置10(不包含)范围内的值1

# 如果元素值不在元组中,则会引起错误
print(tuple1.index(5)) # ValueError: tuple.index(x): x not in tuple

2. 元组操作

2.1 创建

2.1.1 ()创建元组

(item1, item2,…):元组的各个元素置于()内(“()”可以省略),并通过逗号分隔。需要注意的是,当元组中只包含一个元素时,需要在元素后面添加逗号

# 创建空元组
tuple1 = ()

# 赋值创建元组
# 元组里面可以放入任意类型的数据
tuple2 = (1,2,3,4)
tuple3 = ('a', 'b', 'c', 'd')
tuple4 = (1,[2,3],'a',('b','c'))

# ()可以省略
tuple5 = 1,2,3,4
print(tuple5) # (1, 2, 3, 4)

# 当元组中只包含一个元素时,需要在元素后面添加逗号
# 单个元素后面不加逗号,()会被当作运算符
tuple6 = (1)
print(tuple6) # 1
print(type(tuple6)) # <class 'int'>,整数类型
tuple7 = (1,)
print(tuple7) # (1,)
print(type(tuple7)) # <class 'tuple'>,元组类型

2.1.2 tuple()创建元组

tuple(iterable):从可迭代对象(iterable)创建元组,如字符串、列表、字典、range对象等,若为字典,则会将字典的键(key)返回形成元组

# 创建空元组
tuple1 = tuple()
print(tuple1) # ()

# 从字符串创建元组
tuple2 = tuple('python')
print(tuple2) # ('p', 'y', 't', 'h', 'o', 'n')

# 从列表创建元组
tuple3 = tuple([1,2,3,4])
print(tuple3) # (1, 2, 3, 4)

# 从字典创建元组
tuple4 = tuple({'a':1,'b':2,'c':3 ,'d':4})
print(tuple4) # ('a', 'b', 'c', 'd')

# 从range可迭代对象创建元组
tuple5 = tuple(range(10))
print(tuple5) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

# 单个数值无法直接创建元组,因为单个数值不是可迭代对象
tuple(1) # TypeError: 'int' object is not iterable

2.1.3 循环创建元组

由于元组的元素不能被修改,因此元组没有类似于列表的append方法,只能通过连接操作“+”间接实现元组的循环创建

tuple1 = ()
for i in range(10):
    tuple1 += (i,) # 等同于tuple1 = tuple1+(i,)

print(tuple1) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

2.1.4 元组推导式/生成式

(表达式 for 迭代变量 in 可迭代对象 [if 条件表达式] ),if条件表达式为可选参数

元组推导式和列表推导式的用法几乎相同,除了[1]

  • 列表推导式是用中括号[]将推导式括起来,而元组推导式是用小括号()将推导式括起来
  • 列表推导式生成的直接是列表,而元组推导式生成的结果并不直接是一个元组,而是一个生成器对象,需要使用tuple()函数将生成器对象转换为元组
# 列表推导式
list1 = [x for x in range(10)]
print(list1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 元组推导式
tuple1 = (x for x in range(10))
print(tuple1) # <generator object <genexpr> at 0x000001E4011EDDD0>
## 需要进一步使用tuple()函数将生成器对象转换为元组
print(tuple(tuple1)) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

2.2 访问

2.2.1 索引

正向索引(从左往右):索引0开始,0(第1个元素), 1(第2个元素), 2(第3个元素), …
反向索引(从右往左):索引-1开始,…,-1(倒数第1个元素),-2(倒数第2个元素),-3(倒数第3个元素)

当索引值超出元组范围时,则会引起错误。

tuple1 = (1,2,3,4,5,6,7,8,9,10)
print(tuple1[0]) # 1
print(tuple1[1]) # 2
print(tuple1[-1]) # 10
print(tuple1[-2]) # 9
print(tuple1[10]) # IndexError: tuple index out of range

tuple2 = (1,(2,3),'a')
print(tuple2[0]) # 1
print(tuple2[1]) # (2,3)
# 如果需要进一步对[2,3]进行索引
print(tuple2[1][0]) # 2 
print(tuple2[1][1]) # 3

2.2.2 切片

tuple[start: end :step]

  • start:起始索引(包含),默认为0
  • end:结束索引(不包含),默认为-1
  • step:步长(默认为1),步长为正时,从左向右取值;步长为负时,从右向左取值
  • 当步长为正时,start要比end先出现;当步长为负时,start要比end晚出现
tuple1 = (1,2,3,4,5,6,7,8,9,10)

# 选取从第1位开始,到最后1位结束的所有元素(不包含最后1位)
print(tuple1[0:9]) # (1, 2, 3, 4, 5, 6, 7, 8, 9)

# 选取从第1位开始,到最后1位结束的所有元素(不包含最后1位)
print(tuple1[0:-1]) # (1, 2, 3, 4, 5, 6, 7, 8, 9)

# 选取所有元素
print(tuple1[:]) # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# 选取所有元素
print(tuple1[0:]) # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# 选取最后1位之前的所有元素(不包含最后1位)
print(tuple1[:-1]) # (1, 2, 3, 4, 5, 6, 7, 8, 9)

# 选取最后3位元素
print(tuple1[-3:]) # (8, 9, 10)

# 选取从第1位开始,到最后1位结束的所有元素(不包含最后1位),显示表达步长
print(tuple1[0:9:1]) # (1, 2, 3, 4, 5, 6, 7, 8, 9)

# 从第1位开始,到最后1位结束,隔1个挑选1个元素(不包含最后1位)
print(tuple1[0:9:2]) # (1, 3, 5, 7, 9)
print(tuple1[0::2]) # (1, 3, 5, 7, 9)
print(tuple1[:9:2]) # (1, 3, 5, 7, 9)
print(tuple1[::2]) # (1, 3, 5, 7, 9)

# 从最后1位开始的所有元素(相当于倒序)
print(tuple1[::-1]) # (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
print(tuple1[9::-1]) # (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
print(tuple1[-1::-1]) # (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

# 从最后1位开始,隔1个挑选1个元素
print(tuple1[::-2]) # (10, 8, 6, 4, 2)
print(tuple1[9::-2]) # (10, 8, 6, 4, 2)
print(tuple1[-1::-2]) # (10, 8, 6, 4, 2)

# 当步长为正时,start要比end先出现
print(tuple1[9:0:2]) # ()

# 当步长为负时,start要比end晚出现
print(tuple1[0:9:-2]) # ()

2.3 增加

由于元组的元素不能被修改,因此元组没有类似于列表的append、extend、insert等方法,只能通过连接操作“+”间接实现元组元素的增加

# 通过连接操作"+"实现类似list.append()操作
tuple1 = (1,2,3,4)
tuple1 += (5,)
print(tuple1) # (1, 2, 3, 4, 5)

# 通过连接操作"+"实现类似list.insert()操作
tuple1 = tuple1[:2] + (1,) + tuple1[2:]
print(tuple1) # (1, 2, 1, 3, 4, 5)

2.4 删除

只能使用del语句来删除整个元组,而不能只删除一个元素

tuple1 = (1,2,3,4)

# 不能删除元组中的某个(些)元素
del(tuple1[0]) # TypeError: 'tuple' object doesn't support item deletion

# 只能删除整个元素
del(tuple1)
print(tuple1) # NameError: name 'tuple1' is not defined

2.5 遍历

2.5.1 索引遍历

tuple1 = (1,2,3,4,5,6,7,8,9,10)

# 通过索引遍历(不推荐)
for index in range(len(tuple1)):
    print(index) # 0 1 2 3 4 5 6 7 8 9
    print(tuple1[index]) # 1 2 3 4 5 6 7 8 9 10

2.5.2 循环体遍历

tuple1 = (1,2,3,4,5,6,7,8,9,10)

# 通过列表循环体遍历(Pythonic的方式,推荐)
for item in tuple1:
    print(item) # 1 2 3 4 5 6 7 8 9 10

2.6 成员资格

in:检查一个值是否在序列(不仅仅是元组)中,返回布尔运算符

tuple1 = (1,[2,3],'a')
print(1 in tuple1) # True
print(2 in tuple1) # False
print([2,3] in tuple1) # True
print('a' in tuple1) # True
print(a in tuple1) # NameError: name 'a' is not defined

2.7 运算符

  • “+”:元组(不光光是元组,也包括其他序列类型)的连接,具体参考2.1.1.3节和2.1.3节
  • ”*“:元组(不光光是元组,也包括其他序列类型)的重复
tuple1 = (1,2,3)
tuple2 = (4,5)

print(tuple1+tuple2) # (1, 2, 3, 4, 5)
print(tuple2*3) # (4, 5, 4, 5, 4, 5)

2.8 长度

len(seq):内建函数len返回序列(不仅仅是元组)中所包含元素的数量

tuple1 = (1,2,3,4)
tuple2 = (1,2,(3,4))
tuple3 = ('a','b','c','d')
print(len(tuple1)) # 4
print(len(tuple2)) # 3
print(len(tuple3)) # 4

2.9 最值

max(seq):内建函数max返回序列(不仅仅是元组)中最大的元素
min(seq):内建函数min返回序列(不仅仅是元组)中最小的元素

  • 当序列中元素全部为数字时,根据值的大小比较
  • 当序列中元素全部为字符串时,根据每个字符串元素每个字符的 ASCII 的大小比较
  • 当序列中元素为数字和字符串混杂时,则无法比较
# 当序列中元素全部为数字时,根据值的大小比较
tuple1 = (1,2,3,4)
print(max(tuple1)) # 4
print(min(tuple1)) # 1

# 当序列中元素全部为字符串时,根据每个字符串元素的第一个字符的 ASCII 的大小比较
tuple2 = ('I','love','you')
print(max(tuple2)) # you
print(min(tuple2)) # I
print(ord(tuple2[0][0])) # 73
print(ord(tuple2[1][0])) # 108
print(ord(tuple2[2][0])) # 121

# 当序列中元素为数字和字符串混杂时,则无法比较
tuple3 = [1,2,3,4,'I','love','you']
print(max(tuple3)) # TypeError: '>' not supported between instances of 'str' and 'int'
print(min(tuple3)) # TypeError: '<' not supported between instances of 'str' and 'int'

2.10 排序

2.10.1 sorted

sorted(iterable, key=None, reverse=False) :对可迭代对象(不仅仅是元组)进行排序,但是需要注意的是sorted反馈的是列表类型

  • iterable:可迭代对象(不仅仅是元组)
  • key:排序键值
  • reverse:排序顺序,reverse=True降序,reverse=False升序(默认)
tuple1 = (1,3,4,2)
tuple2 = ('one','two','three','four')
tuple3 = (2,1,'b','a')

# 数值排序
print(sorted(tuple1)) # [1, 2, 3, 4],升序排列
print(sorted(tuple1,reverse=True)) # [4, 3, 2, 1],降序排列

# 字符串排序
print(sorted(tuple2)) # ['four', 'one', 'three', 'two'],具体为什么这么排序,参考下面各个字母的ASCII编码大小,也就是各个字母的先后顺序
print('f:%d'% ord('f')) # f:102
print('o:%d'% ord('o')) # o:111
print('t:%d'% ord('t')) # t:116
print('h:%d'% ord('h')) # h:104
print('w:%d'% ord('w')) # w:119

# sort不支持数值和字符串混合的排序
sorted(tuple3) # TypeError: '<' not supported between instances of 'str' and 'int'

# 给定排序键值排序
print(sorted(tuple2,key=lambda x: x[0])) # ['four', 'one', 'two', 'three'],按照首字母顺序升序排列
print(sorted(tuple2,key=lambda x: x[1],reverse=True)) # ['two', 'four', 'one', 'three'],按照第二个字母顺序降序排列

2.10.2 倒序

元组没有类似列表reverse的方法,只能通过切片tuple[::-1]间接实现元组元素的倒序排列

tuple1 = (1,2,3,4,5)
print(tuple1[::-1]) # (5, 4, 3, 2, 1)

Reference

[1]: http://c.biancheng.net/view/4443.html
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值