What does the asterisk do in Python other than multiplication and exponentiation? [duplicate]

别说谁变了你拦得住时间么 提交于 2019-12-01 03:19:03

问题


In Peter Norvig's Lisp interpreter written in Python (http://norvig.com/lispy.html), he defines Lisp's eval as follows:

def eval(x, env=global_env):
    "Evaluate an expression in an environment."
    if isa(x, Symbol):             # variable reference
        return env.find(x)[x]
    elif not isa(x, list):         # constant literal
        return x                
    elif x[0] == 'quote':          # (quote exp)
        (_, exp) = x
        return exp
    elif x[0] == 'if':             # (if test conseq alt)
        (_, test, conseq, alt) = x
        return eval((conseq if eval(test, env) else alt), env)
    elif x[0] == 'set!':           # (set! var exp)
        (_, var, exp) = x
        env.find(var)[var] = eval(exp, env)
    elif x[0] == 'define':         # (define var exp)
        (_, var, exp) = x
        env[var] = eval(exp, env)
    elif x[0] == 'lambda':         # (lambda (var*) exp)
        (_, vars, exp) = x
        return lambda *args: eval(exp, Env(vars, args, env))
    elif x[0] == 'begin':          # (begin exp*)
        for exp in x[1:]:
            val = eval(exp, env)
        return val
    else:                          # (proc exp*)
        exps = [eval(exp, env) for exp in x]
        proc = exps.pop(0)
        return proc(*exps)

isa = isinstance

Symbol = str

This line in particular interests me:

return proc(*exps)

What is the asterisk in from of exps doing exactly?


回答1:


Single asterisk in before a seqable object unpacks it, like Joran showed:

In [1]: def f(*args): return args

In [2]: f(1,2,3)
Out[2]: (1, 2, 3)

In [3]: f(*[1,2,3,4])
Out[3]: (1, 2, 3, 4)

(Note a third application for *: in function definition an asterisk indicates a variable length list of arguments, all are being packed into one list, args, in In [1])

Also worth noting is that a double asterisk (**) does a dictionary unpacking:

In [5]: def g(foo=None, bar=42): return foo,bar

In [6]: g()
Out[6]: (None, 42)

In [7]: g(*[1,2])
Out[7]: (1, 2)

In [8]: g(**{'foo': 'FOO', 'bar': 'BAR'})
Out[8]: ('FOO', 'BAR')



回答2:


it unpacks the arguments

function(1,2,3)  ==  function(*[1,2,3])

it makes it easy to use variables to pass in to functions

args = [1,2,3]
func(*args) #much nicer than func(args[0],args[1],args[2],...)


来源:https://stackoverflow.com/questions/16515443/what-does-the-asterisk-do-in-python-other-than-multiplication-and-exponentiation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!