元组及其基本操作

本文介绍了Python中元组的基本概念,包括定义、常见操作如索引取值、切片及内置函数的使用等。同时探讨了如何定义单元素元组,并通过实例展示了元组的多种创建方式。

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

元组

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

结果:() <class 'tuple'>

  

  参数为for可以循环的对象(可迭代对象)

t2 = tuple("123")
print(t2, type(t2))  #('1', '2', '3') <class 'tuple'>
t3 = tuple([1, 2, 3])
print(t3, type(t3))  #(1, 2, 3) <class 'tuple'>
t4 = tuple((7, 8, 9))
print(t4, type(t4))  #(7, 8, 9) <class 'tuple'>

  

 思考:如何定义一个只有一个值的元组

# "Owen"
print(("Owen", ))
print(tuple(['Owen']))

 常用操作
 元组有序存储
 索引取值

t = (1, 2, 3, 2, 3, 2)
print(t[1])   #2
print(t[-2])  #3

  切片

t = (1, 2, 3, 2, 3, 2)
print(id(t))  #2129098784520
nt = t[:-1:]
print(nt, id(nt))  #(1, 2, 3, 2, 3) 2129098421328

 长度

t = (1, 2, 3, 2, 3, 2)
print(len(t))   #6

 

内置函数的操作

tuple.count(元素,起始索引,终止索引):统计元素,返回元素个数

t = (1, 2, 3, 2, 3, 2)
i=t.count(2)
print(i)   #3  元组中2的个数有3个

tuple.index(元素,起始索引,终止索引)查找元素,返回找到的第一个索引(找不到会报错)

 

t = (1, 2, 3, 2, 3, 2)
i=t.index(3)
print(i)   #2  返回的是元组中第一个3的位置索引

  

转载于:https://www.cnblogs.com/tuzaizi/p/10612412.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值