元组

元组

1.特点

  • 有序

  • 可重复

    • 好处值不会改变可以减少很多报错。
  • 不可改变

    • 若元组里面有列表,则可以修改元组中的列表
    tp=(1,2,3,4,5,6,7,8,['abc','def','qwe'])
    print(id(tp))
    tp[-1][1]='ok'
    print(tp)
    print(id(tp))
    #输出
    91638320
    (1, 2, 3, 4, 5, 6, 7, 8, ['abc', 'ok', 'qwe'])
    91638320
    

2.定义

  • 元组使用小括号,列表使用方括号。
  • 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

3.创建

  • 空元组的创建
tp=()
tp1=tuple()
print(type(tp))
print(type(tp1))
#输出
<class 'tuple'>
<class 'tuple'>
  • 单元素元组的创建

str1=('abc')
tp=('abc',)
print(type(str1))
print(type(tp))

#输出
<class 'str'>
<class 'tuple'>

4.拼接

tp=(1,2,3,4)
tp1=(5,6,7,8)
print(tp+tp1)
#输出
(1, 2, 3, 4, 5, 6, 7, 8)

5.重复

tp=(1,2,3,4)
print(tp*3)
#输出
(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)

6.索引(偏移)

tp=(1,2,3,4)
print(tp[2])
print(tp[-1])
#输出
3
4

7.切片

tp=(1,2,3,4,5,6,7,8)
print(tp[1:5:2])
print(tp[-4:-1:1])
print(tp[0:])
print(tp[::-1])
#输出
(2, 4)
(5, 6, 7)
(1, 2, 3, 4, 5, 6, 7, 8)
(8, 7, 6, 5, 4, 3, 2, 1)

8.查

8.1索引查

  • index()
tp = ('a','b','c','d','e','f')
print(tp.index('d'))
#输出
3

8.2切片查

tp=(1,2,3,4,5,6,7,8)
print(tp[1:5:2])
print(tp[-4:-1:1])
print(tp[0:])
print(tp[::-1])
#输出
(2, 4)
(5, 6, 7)
(1, 2, 3, 4, 5, 6, 7, 8)
(8, 7, 6, 5, 4, 3, 2, 1)

9 删除

  • 删除某个元素,不能
  • 删除全部元素,包括元组本身。
    • del相当于把变量放到垃圾站中,短时间内赋同样的值,id是不会发生改变的。长时间后会释放内存。
tp = ('a','b','c','d','e','f')
del tp
print(tp)
#输出
会报错,tp未定义

10.最大值与最小值

tp = ('a','b','c','d','e','f')
print(max(tp),min(tp))
#输出
f a

11.遍历

  • 元素遍历

  • 索引遍历

  • 枚举遍历

tp = ('a', 'b', 'c', 'd', 'e', 'f')
for i in tp:
    print(i, end=' ')
print('')
for i in range(len(tp)):
    print(tp[i], end=' ')  #python中()括号一般都表示函数,切片使用的都是[]括号,所以即使元组使用()                            #定义,切片时依然使用[]。	
print('')
for i in enumerate(tp,1):
    print(i)
#输出
a b c d e f 
a b c d e f 
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')
(6, 'f')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值