• python arguments *args and **args ** is for dictionaries, * is for lists or tuples.


    below is a good answer for this question , so I copy on here for some people need it

    By the way, the three forms can be combined as follows: def f(a,*b,**c):

    All single arguments beyond the first will end up with the tuple b, and all key/value arguments will end up in dictionary c.

    For example, f(1,2,3,4,5,d=6,e=7,f=8) should put 1 in a, (2,3,4,5) in b, and {‘d’:6,’e':7,’f':8} in c.

    Let’s see if it does. Let’s define f first:

    >>> def f(a,*b,**c):print a,b,c

     Now, let’s call the function:

    >>> f(1,2,3,4,5,d=6,e=7,f=8)

    1 (2, 3, 4, 5) {‘e’: 7, ‘d’: 6, ‘f’: 8}

    test(x)

    test(*x)

    test(**x)

    >>> x=(1,2,3)

    >>> test(x)

    Traceback (most recent call last): File “”, line 1, in ?

    TypeError: test() takes exactly 3 arguments (1 given)

    Again, as expected. We fed a function that expects 3 arguments with only one argument (a tuple with 3 items), and we got an error.

    If we want to use the items in the sequence, we use the following form:

    >>> test(*x)

    1 2 3

    There, x was split up, and its members used as the arguments to test. What about the third form?

    >>> test(**x)

    Traceback (most recent call last): File “”, line 1, in ?

    TypeError: test() argument after ** must be a dictionary

    It returned an error, because ** always refers to key/value pairs, i.e., dictionaries.

    Let’s define a dictionary then:

    >>> x={‘a’:1,’b':2,’c':3}

    >>> test(**x) 1 2 3

    >>> test(*x)

    a c b

    Ok. The first call passed on the values in the dictionary.

    The second call passed on the keys (but in wrong order!).

    Remember, ** is for dictionaries, * is for lists or tuples.

  • 相关阅读:
    创龙OMAPL138开发板测试Device is held in reset. Take the device out of reset, and retry the operation.
    大数据基础之HDFS
    分布式系统文章汇总
    大数据漫谈
    SQL与Database
    大数据基础之YARN
    大叔经验分享(141)ElasticSearch优化实践
    大数据基础之Hive
    算法工程漫谈
    【SI】source insight4 添加指定类型的文件
  • 原文地址:https://www.cnblogs.com/juandx/p/4936251.html
Copyright © 2020-2023  润新知