tuple拆包操作

"""

tuple 是不可变对象

"""

user_tuple = ('admin', 18, "cd", "male")
print(user_tuple)

# tuple 拆包

name, age, address, gender = user_tuple
print(name, age, address, gender)  # admin 18 cd male

#  也可以这样拆包
name, *other = user_tuple
print(name, other)  # admin [18, 'cd', 'male']

'''
  tuple的不可变性是因为tuple里面的元素也是具有不可变性,
  如果tuple中的元素放一个list,那么也是可以变的,
  不过,不推荐在tuple中放置list
  请看下面示例
'''

t = ('person', ['admin', 18])
print(t)  # ('person', ['admin', 18])

t[1].append('cd')
print(t)  # ('person', ['admin', 18, 'cd'])

# tuple中的list元素发生了变化,但是这个list的id值还是不变的

"""

tuple与list 相比,优势:
1. 性能优化
2. 线程安全
3. 可以作为dict的key, 只有不可变对象才能成为dict的key
4. 拆包,使用方便
"""

猜你喜欢

转载自www.cnblogs.com/z-qinfeng/p/12037625.html