拆包、交换变量的值
<1> 对返回的数据直接拆包
def get_my_info(): high = 178 weight = 100 age = 18 return high, weight, age # result = get_my_info() # print(result) my_high, my_weight, my_age = get_my_info() print(my_high) print(my_weight) print(my_age)
总结:
- 拆包时要注意,需要拆的数据的个数要与变量的个数相同,否则程序会异常
-
除了对元组拆包之外,还可以对列表、字典等拆包
In [17]: a, b = (11, 22) In [18]: a Out[18]: 11 In [19]: b Out[19]: 22 In [20]: a, b = [11, 22] In [21]: a Out[21]: 11 In [22]: b Out[22]: 22 In [23]: a, b = {"m":11, "n":22} # 取出来的是key,而不是键值对 In [24]: a Out[24]: 'm' In [25]: b Out[25]: 'n'
<2> 交换2个变量的值
# 第1种方式 # a = 4 # b = 5 # c = 0 # # c = a # a = b # b = c # # print(a) # print(b) # 第2种方式 # a = 4 # b = 5 # a = a+b # a=9, b=5 # b = a-b # a=9, b=4 # a = a-b # a=5, b=4 # print(a) # print(b) # 第3种方式 a, b = 4, 5 a, b = b, a print(a) print(b)
例子1:
# 比较python的写法 # 01: # 名字 年龄 学号 # my_name = "小明" # my_age = 18 # my_no = "007" # 优化 # 变量数量和数值的数量必须一致 而且需要位置一一对应 my_name, my_age, my_no = "小明", 18, "007"
例子2:
# 02: a = 5 # if a >= 0 and a <= 10: # pass # # 优化 if 0 <= a <= 10: pass
例子3(拆包):
# 拆包 # 01: # 定义一个列表 # my_list = ["小明", 18, "007"] # # print(my_list[0]) # print(my_list[1]) # print(my_list[2]) # 拆包 my_name, my_age, my_no = ["小明", 18, "007"] print(my_name)
例子4(拆包):
# 02: # 同事定义了一个元组 my_tuple = (123, 3.14) # 使用下标索引 # my_tuple[0] # 拆包 num1, num2 = my_tuple print(num2)
例子5(拆包):
# 03: def deal_info(name, age): # 定义两个变量 my_name = "我的名字叫做" + name my_age = "我的年龄为%d岁" % age return my_name, my_age new_name, new_age = deal_info("小明", 18) print(new_name)
思考: 哪些数据类型可以进行拆包
# str list tuple a, b = "ab" print(b)
# 字典 name, age = {"name": "小明", "age": 19} print(name)
# 集合 v1, v2 = {1, 3} print(v2) # range