Python是一门解释性语言,也就是会将程序先编译成字节码PyC,PVC的加载速度会比较快。

Pupil的进阶讲解。

tuple的功能:
不可变、iterable
拆包
tuple不可变性不是绝对的(所以放进tuple中的元素最好是不可变的)
tuple比list好的地方
immutable(不可变)的重要性
性能优化:元素全为immutable的tuple会作为常量在编译时确定
线程安全(tuple本身加锁)
可以作为dict的key
拆包特性
user_tuple = ("bobby",29)
name,age = user_tuple
==>bobby 29
user_tuple = ("bobby",29,175,"beijing","edu")
name, *other = user_tuple
print(name,other)
==>bobby [29, 175, 'beijing', 'edu']
tuple:不可变,可迭代对象iterable(实现了__iter__或者__getitem__魔法函数)
元祖的拆包:
用法:
user_tuple = ("bobby", 28, 178)
name, age, height = user_tuple
只想提取第一个参数:
name, *other = user_tuple
输出:
bobby, [29, 175]
tuple的不可变不是绝对的:
tuple内部嵌套了可变对象(不太建议使用),嵌套对象可修改
tuple比list好用的地方:
immutable(不可变对象)的重要性:
①性能优化(元素全部为不可变对象的tuple会作为常量在编译时确定,因此产生如此显著的速度差异)
②线程安全
③可以作为dict的key(immutable对象是可哈希的,dict key也是可哈希的,适合做字典的key)
使用list做key会报错提示:TypeError: unhashable type: 'list'
④拆包特性
如果拿c语言类比,tuple好比struct,list对应的是array
tuple的优点:
可以作为dict的key,
tuple:元组,不可变,可迭代,可拆包
girl = ("珊珊", 21, 170, "B罩杯")
name,age,height,cupSize = girl # 元组拆包
print(name, age, height, cupSize)其不可变不是绝对的,当元组中包含数组或其他可变数据对象时,就可以改变元组的内容。
tuple比list好,原因:
其不可变性,可以保证在编译时确定其值,使得性能优化,线程安全,可以作为dict的key,具有拆包特性
如果要拿C语言来类比,Tuple对应的是struct(结构体),而list对应的是array(数组)
tuple比list好的地方
拆包的用法2
拆包的用法
tuple的功能
hjijojiiojio
Tuple的特性
tuple的拆包特性:
tuple = (1,2,3,4,5)
a,b,c,d,e = tuple
a, *ot = tuple
dict的 key必须是可哈希的,而tuple是iter对象中可哈希的类型,因此,tuple可以用作dict的key
#拆包特性
user_tuple = ("bobby", 29, 175)
name, age, height = user_tuple
print(name, age, height) #-->bobby 29 175
user_tuple = ("bobby", 29, 175, "beijing")
name, *other = user_tuple
print(name, other) #-->bobby [29, 175, "beijing"]
#元组的不可变不是绝对的
name_tuple = ("bobby1", [29, 175])
name_tuple[1].append(22)
print(name_tuple) #("bobby1", [29, 175, 22])
#tuple是可哈希的,可以当做dict的key;而数组list不可以
user_info_dict = {}
user_info_dict[user_tuple] = "bobby"
#namedtuple
from collections import namedtuple
User = namedtuple("User", ["name", "age", "height"]) #创建class“User”,并传递属性"name", "age", "height"]
user = User(name="bobby", age=29, height=175) #也可使用下面两种方式进行初始化
print(user.age, user.name, user.height) #像使用类一样
#使用tuple进行初始化
user_tuple = ("bobby", 29, 175)
user = User(*user_tuple) #加*代表依次传递tuple(*args:未指明变量名)
#使用dict进行初始化
user_dict = {"name":"bobby", "age":29, "height":175}
user = User(**user_dict) #加**代表依次传递dict(**kwargs:指明变量名和值)
#也可使用_make函数省去*和**,_make函数支持可迭代iterable的对象:list、tuple、dict
user = User._make(user_tuple)
user = User._make(user_list)
user = User._make(user_dict)
基础collections中的数据结构
nameddict
tuplelist
tuble功能
python变量的实质,只是一种符号?
tuple的重要性