python:08_元组

元组定义

python的元组与列表类似,也是容器的一种,不同之处在于元组的元素不能修改

元组的类型为tuple,用一对()表示,中间用分隔。

names = ('itcast','itheima','bxg')
print(names)
print(type(names))
('itcast', 'itheima', 'bxg')
<class 'tuple'>

错误的实例

 #错误的实例
names = ('itcast')
print(names)
print(type(names))
itcast
<class 'str'>

元组一定要有小括号包裹和逗号分隔。

 #正确的实例
names = ('itcast',)
print(names)
print(type(names))
('itcast',)
<class 'tuple'>

访问元组的元素(索引)

#访问元组的元素
names = ('itcast','itheima','bxg')
print(names[1])
itheima

获取索引

#获取索引
names = ('itcast','itheima','bxg')
index = names.index('itheima')
print(index)
1

元组不能添加元素(append())和修改(删除,排序)元素

names = ('itcast','itheima','bxg')
names.append('czxy')
print(names)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-07c8a2d05999> in <module>
      1 #添加元素
      2 names = ('itcast','itheima','bxg')
----> 3 names.append('czxy')
      4 print(names)

AttributeError: 'tuple' object has no attribute 'append'

#修改元素
names = ('itcast','itheima','bxg')
names[1] = 'czxy'
print(names)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-999951aa1874> in <module>
      1 #修改元素
      2 names = ('itcast','itheima','bxg')
----> 3 names[1] = 'czxy'
      4 print(names)

TypeError: 'tuple' object does not support item assignment

元组具有自动组组包和解包功能以及交换功能

#自动组包
names = 'itcast','bxg','itheima'
print(names)
print(type(names))
('itcast', 'bxg', 'itheima')
<class 'tuple'>

#自动解包
names = ('itcast','itheima','bxg')
names1,names2,names3=names
print(names1)
print(names2)
print(names3)
itcast
itheima
bxg

#传统交换做法
a = 10
b = 5
t = a
a = b
b = t
print("a = {},b = {}".format(a,b))
a = 5,b = 10

#元祖交换功能
a = 10
b = 5
a,b = b,a
print("a = {},b = {}".format(a,b))
a = 5,b = 10

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值