0
点赞
收藏
分享

微信扫一扫

Python基础学习-7.元组

7.元组

python内置的数据结构之一,是不可变序列。

不可变序列与可变序列

不变可变序:字符串、元组
   不变可变序列:没有增、删、改的操作
可变序列:列表、字典
   可变序列:可以对序列执行增、删、改操作,对象地址不发生更改

eg1:

print('------可变序列 列表,字典------------')
lst=[10,20,45]
print(id(lst))
lst.append(300)
print(id(lst))

print('------不可变序列:字符串,元组---------')
s='good'
print(id(s))
s=s+'day'
print(id(s))
print(s)

========================>
------可变序列 列表,字典------------
2014103296704
2014103296704
------不可变序列:字符串,元组---------
2014103331120
2014103624816
goodday

7.1元组的创建

元组的创建方式

小括号():t=('python','hello','100')

使用内置函数tuple(): t=tuple(('python','hello','100'))

只包含一个元组的元素需要使用逗号和小括号: t=(10,)

eg1:

#元组的创建方式
#第一种
t=('Python','world',90)
print(t)
print(type(t))

#第二中方式
t1=tuple(('python','hello',90))
print(t1)
print(type(t1))

t2='python','world',90
print(t2)
print(type(t2))

#t3=('python')    #只有一个元素不加逗号是str类型
t3=('python',)    #只有一个元素加逗号是元组
print(t3)
print(type(t3))

print('---空元组----')
t4=()
t5=tuple()
print('空元组',t4,t5)

print('----空列表-----')
lst=[]
lst1=list()
print('空列表',lst,lst1)

print('-----空字典-----')
d={}
d2=dict()
print('空字典',d,d2)

================================》
('Python', 'world', 90)
<class 'tuple'>
('python', 'hello', 90)
<class 'tuple'>
('python', 'world', 90)
<class 'tuple'>
('python',)
<class 'tuple'>
---空元组----
空元组 () ()
----空列表-----
空列表 [] []
-----空字典-----
空字典 {} {}

为什么将元组设计成不可变序列?

在多任务环境下,同时操作对象时不需要加锁,所以在程序中尽量使用不可变序列。

注意:

元组中存储的是对象的引用
如果元组中对象本身是不可变对象,则不能再引用其它对象
如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可改变

eg:

t=(10,[20,30],9)
print(t)
print(type(t))
print(t[0],type(t[0]),id(t[0]))
print(t[1],type(t[1]),id(t[1]))
print(t[2],type(t[2]),id(t[2]))

'''尝试将t[1]修改为100'''
print(id(100))
#t[1]-100 元组是不允许修改元素的
'''由于[20,30]列表,而列表是可变序列,所以可以向列中添加元素,而列表的内存地址不变'''
t[1].append(100)
print(t,id(t[1]))

===================================>
(10, [20, 30], 9)
<class 'tuple'>
10 <class 'int'> 2613553228368
[20, 30] <class 'list'> 2613555116928
9 <class 'int'> 2613553228336
2613553419728
(10, [20, 30, 100], 9) 2613555116928

7.2元组的遍历

元组是可迭代对象,所以可以使用for...in进行遍历

eg;

t=tuple(('python','hello',80))
'''获取元组的方式1:使用索引'''
print(t[0])
print(t[1])

'''获取元组的方式2:遍历'''
for item in t:
    print(item)

7.3总结

元组的创建:使用()小括号,内置函数tuple()
元组的遍历:fo...in
不可变序列
举报

相关推荐

0 条评论