Python星号*(乘法或不确定的参数)与**(指数运算或不确定的字典类参数)用法分析

本文实例分析了Python星号*与**用法。分享给大家供大家参考,具体如下:

1. 加了星号(*)的变量名会存放所有未命名的变量参数,不能存放dict,否则报错。

如:

?

1

2

3

4

5

6

7

扫描二维码关注公众号,回复: 3424420 查看本文章

def multiple(arg, *args):

  print "arg: ", arg

  #打印不定长参数

  for value in args:

    print "other args:", value

if __name__ == '__main__':

  multiple(1,'a',True)

输出:

2. 加了星号(**)的变量名会存放所有未命名的变量参数

?

1

2

3

4

5

6

def multiple2(**args):

  #打印不定长参数

  for key in args:

    print key + ":" + bytes(args[key])

if __name__ == '__main__':

  multiple2(name='Amy', age=12, single=True)

输出

3. 有 *args 和 **dictargs:

?

1

2

3

4

5

6

7

8

9

10

def multiple(arg, *args, **dictargs):

  print "arg: ", arg

  #打印args

  for value in args:

    print "other args:", value

  #打印dict类型的不定长参数 args

  for key in dictargs:

    print "dictargs:" + key + ":" + bytes(dictargs[key])

if __name__ == '__main__':

  multiple(1,'a',True, name='Amy',age=12, )

输出:

另外,在Python数学运算中*代表乘法,**为指数运算,示例代码如下:

?

1

2

3

4

5

>>> 2*4

8

>>> 2**4

16

>>>

 https://www.jb51.net/article/134240.htm

猜你喜欢

转载自blog.csdn.net/qq_27361945/article/details/82758153
今日推荐