注意, 本文的打包和解包的概念有点类似与java 的装箱和解箱
但是还是有点区别
java 中的装箱指的是 把一系列的值让放入1个对象的属性中
而python的打包概念 包括
- 把一组元素打包成1个list or tuple
- 把一系列 key value pair 打包成1个dict
Python * 的基本功能, 乘法
* 首先是1个人乘法符号 例如
from loguru import logger
def process():
logger.info(3 * 12) # 36
logger.info("hello" * 3) # hellohellohello
logger.info([1, 2, 3] * 3) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
logger.info(["a", "b", "c"] * 3) # ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
logger.info("hello" * "world") # TypeError: can't multiply sequence by non-int of type 'str'
if __name__ == "__main__":
import src.configs.config
process()
直接的注意的是, * 的乘法不单止 数字乘数字
还包括字符串 乘 整数, 数组乘整数
但是不support string * string , string * float , string * 数组, 数组 * 数组等
* 的打包功能
第1个例子
def sample1():
list_num = [1, 2, 3]
first, second, rest = list_num
logger.info("first is {}".format(first)) # 1
logger.info("second is {}".format(second)) # 2
logger.info("rest is {}".format(rest)) # 3
上面的例子就是一个简单的解包例子
我们用3个变量去接受1个3个元素的数组是可以正常给3个变量赋值的
2024-05-05 23:53:25.407 | INFO | __main__:sample1:6 - first is 1
2024-05-05 23:53:25.407 | INFO | __main__:sample1:7 - second is 2
2024-05-05 23:53:25.407 | INFO | __main__:sample1:8 - rest is 3
第2个例子
这时如果我改写成让3个变量去接受