python基础七

元组

1.Python内置的数据结构之一,是一个不可变序列
2.t = (‘python’, ‘hello’, 90) # 元组与列表的格式不同在于 列表是中括号[],而元组是小括号()

不可变序列与可变序列

1.不变序列:字符串,元组(都没有增,删,改的操作,如果操作,则对象地址发生改变)
2.可变序列:列表,字典(可以对序列执行增,删,改操作,对象地址不发生更改)

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

# 不可变序列  字符串,元组
s = 'hello'
print(id(s))    # 2379559875184
s = s + 'world'
print(id(s))    # 2379560165296
print(s)

元组的创建方式

1.直接小括号
t = (‘python’, ‘hello’, 90)
2.使用内置函数tuple()
t = tuple(‘python’, ‘hello’, 90)
3.只包含一个元组的元素需要使用逗号和小括号
t = ( 10, )

# 第一种创建方式,使用 ()
t = ('python', 'world', 98)
print(t)
print(type(t))

t2 = 'python', 'world', 98  # 省略了小括号
print(t2)
print(type(t2))

# t3 = ('python')       # 如果元组中只有一个元素,逗号不能省略
# print(type(t3), t3)     # <class 'str'> python
t3 = ('python', )
print(type(t3), t3)     # <class 'tuple'> ('python',)

# 第二种创建方式,使用内置函数tuple()
t1 = tuple(('python', 'world', 98))
print(t1)
print(type(t1))

# 空列表的创建
lst1 = []
lst2 = list()
print(lst1, lst2)
# 空字典的创建
d1 = {}
d2 = dict()
print(d1, d2)
# 空元组的创建
t4 = ()
t5 = tuple()
print(t4, t5)

将元组设计成不可变序列

原因:
1.在多任务环境下,同时操作对象时不需要加锁
2.因此,在程序中尽量使用不可变序列
注意事项:
1.元组中存储的是对象的引用
2.如果元组中对象本身不可变对象,则不能再引用其他对象
3.如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变

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      # TypeError: 'tuple' object does not support item assignment
# 元组是不允许修改元素的
"""由于[20, 30]是列表,而列表是可变序列,所以可以向列中添加元素,而列表的内存地址不变"""
t[1].append(100)    # 向列表中添加元素
print(t[1], id(t[1]))

元组的遍历

元组是可迭代对象,所以可以使用for…in进行遍历
t = tuple(‘python’, ‘hello’, 90)
for item in t:
print(item)

# 第一种获取元组元素的方式,使用索引
t = ('python', 'hello', 90)
print(t[0])
print(t[1])
print(t[2])
# print(t[3])     # IndexError: tuple index out of range
# 第二种获取元组元素的方式,使用for...in
for item in t:
    print(item)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值