什么是拆包
拆包: 对于函数中的多个返回数据, 去掉元组, 列表 或者字典 直接获取里面数据的过程.
怎么拆包
my_list = [1, 3.14, "hello", True] num, pi, my_str, my_bool = my_list # 或者 num, pi, my_str, my_bool = [1, 3.14, "hello", True]
my_tuple = (1, 3.14, "hello", True) num, pi, my_str, my_bool = my_tuple
my_dict = {"name":"老王", "age": 19} ret1, ret2 = my_dict # 得到的是key 字典是无序的 print(ret1, ret2)
结果
name age
# 一次定义多个变量 num1 = 10 num2 = 20 num3 = 30 num4 = 3.14 # # 变量名和值是一一对应 num1, num2, num3, num4 = 10, 20, 30, 3.14
def get_my_info(): high = 178 weight = 100 age = 18 return high, weight, age # 这一步叫做拆包: my_high, my_weight, my_age = get_my_info() print(my_high) print(my_weight) print(my_age)
结果
178 100 18
也可以对列表或者字典拆包:
def function1(): return [1, 2, 3] def function2(): return {"key1": 1, "key2": 2, "key3": 3} # 调用函数,获取里面的数据 num1, num2, num3 = function1() print(num1, num2, num3) # 调用函数,获取里面的数据 ret1, ret2, ret3 = function2() print(ret1, ret2, ret3)
结果:
1 2 3
key1 key2 key3
除了对元组拆包之外,还可以对列表、字典等拆包
对字典拆包后获取的是字典的key值, 而不是value值