python中,* 号除了用来作数量乘法,还有其余的用处。python
def func3(a, b, c): print("param a is {}, param b is {}, param c is {}".format(a, b, c)) if __name__ == '__main__': arr1 = [1, 2, 3] print(arr1, sep='\t') # [1, 2, 3]\t 正常输出 print(*arr1, sep='\t') # 1\t2\t3 每一个数字中间以\t分割 arr2 = [[1, 2, 3], [3, 4, 5], [5, 6, 7]] print(list(zip(*arr2))) # [(1, 3, 5), (2, 4, 6), (3, 5, 7)] 二维数组的行转列 dictionary = {'a': 1, 'b': 2, 'c': 3} print(dictionary, sep='\t') # {'a': 1, 'b': 2, 'c': 3}\t 正常输出 print(*dictionary, sep='\t') # a\tb\tc\t 每一个字母中间以\t分割 print(func3(**dictionary)) # param a is 1, param b is 2, param c is 3
比较使用和不使用*号后产生的结果就能够发现,单*号将可迭代对象进行了拆分,按单个元素方式依次将数据传进方法。
配合其余方法使用能够优雅的完成矩阵的行转列操做。git
双**号的使用,是将变量对象拆分红键值对的形式,因此只有dict类型可使用。
注意上面的func3,他须要三个形参,可是咱们只传入**dict_obj, 就完成了功能。github
可迭代对象有:list, dict, tuple, generator, iterator数组
def func1(*args): print("type", type(args)) # type <class 'tuple'> print("all arguments: ", args) # all arguments: (1, 2, 3) print("second argument: ", args[1]) # second argument: 2 def func2(**kw): print("type", type(kw)) # type <class 'dict'> print("all arguments: ", kw) # all arguments: {'a': 1, 'b': 2, 'c': 3} print("second argument: ", kw['a']) # second argument: 1 if __name__ == '__main__': a, b, c = 1, 2, 3 func1(a, b, c) func2(a=a, b=b, c=c)
尽管函数func1的形参只有一个,但被传递三个参数,程序仍是能够正常运行。
由于*args将三个参数以tuple形式存储,做为一个总体传递给方法func1。函数
同理,func2的**kw形参将传入的三个参数压成一个dict进行使用。code
具体实验代码能够经过Github得到。orm