Python学习笔记-元组

本文详细探讨了Python中的元组,包括其作为不可变有序集合的特性、固定长度、异构数据支持、嵌套使用以及如何进行索引、切片、合并等操作。还介绍了元组在成员关系判断、迭代和搜索计数等方面的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 元组属性
    1.任意对象的有序集合
    2.通过偏移存取
    3.属于不可变序列类型
    4.固定长度,异构,任意嵌套
    5.对象引用的数组

  • 元组常用方法
    1.单个元素的元组

T = (0,) #注意逗号的使用
L = (0)
print('T is {}, type is {}'.format(T,type(T)))
print('L is {}, type is {}'.format(L,type(L)))

运行结果:

T is (0,), type is <class 'tuple'>
L is 0, type is <class 'int'>

2.4个元素的元组

T = (0,'bb',3,3.4)
L = 0,'bb',3,3.4   #这里没有使用括号,另一种定义元组的方式
print('T is {}, type is {}'.format(T,type(T)))
print('L is {}, type is {}'.format(L,type(L)))

运行结果:

T is (0, 'bb', 3, 3.4), type is <class 'tuple'>
L is (0, 'bb', 3, 3.4), type is <class 'tuple'>

3.元组嵌套

T = ('abc',('b','cd'))
print('T is {}, type is {}'.format(T,type(T)))
print('T[1] is {}, type is {}'.format(T[1],type(T[1])))

运行结果:

T is ('abc', ('b', 'cd')), type is <class 'tuple'>
T[1] is ('b', 'cd'), type is <class 'tuple'>

4.可迭代对象的元素构成的元组

T = tuple('hello')
print('T is {}, type is {}'.format(T,type(T)))

运行结果:

T is ('h', 'e', 'l', 'l', 'o'), type is <class 'tuple'>

5.索引,分片,长度,索引的索引

T = tuple('hello')
val = T[0]
print('索引为0时,元组的元素是'+val)
val2 = T[1:3] #分片
print('索引为1~2时,元组的元素是{}'.format(val2))
length = len(T)
print('T元组有元素{}个'.format(length))

L = (1,(2,3),4,(5,6))
val = L[1][1]
print('索引的索引,{}'.format(val))

运行结果:

索引为0时,元组的元素是h
索引为1~2时,元组的元素是('e', 'l')
T元组有元素5个
索引的索引,3

6.合并,重复

T = tuple('hello')
L = (1,(2,3),4,(5,6))
N1 = T + L
N2 = T * 2
print('元组合并操作得到N1元组{}'.format(N1))
print('元组重复操作得到N2元组{}'.format(N2))

运行结果:

元组合并操作得到N1元组('h', 'e', 'l', 'l', 'o', 1, (2, 3), 4, (5, 6))
元组重复操作得到N2元组('h', 'e', 'l', 'l', 'o', 'h', 'e', 'l', 'l', 'o')

7.成员关系判断

T = tuple('hello')
if 'o' in T:
    print('o 在 N2元组里{}'.format(T))
if 'lo' not in T:
    print('lo 不在 N2元组里{}'.format(T))

运行结果:

o 在 N2元组里('h', 'e', 'l', 'l', 'o')
lo 不在 N2元组里('h', 'e', 'l', 'l', 'o')

8.迭代

T = tuple('hello')
for x in T:
    print('打印元素元素:{}'.format(x))

运行结果:

打印元素元素:h
打印元素元素:e
打印元素元素:l
打印元素元素:l
打印元素元素:o

9.搜索、计数

T = tuple('hello')
index = T.index('e') #返回第一次出现的索引
count = T.count('l')
print('T元组中e元素的索引{},l元素个数{}'.format(index, count))

运行结果:

T元组中e元素的索引1,l元素个数2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值