2015-04-04 40 views
1

我必须在Python中创建一个包含两个以上参数的函数,最后我必须打印该函数的第一个和最后一个参数(在列表中)。在Python中获取第一个和最后一个函数参数

我试过这样,但它不起作用。我究竟做错了什么?

import inspect 

def func(a, b, c): 
    frame = inspect.currentframe() 
    args, _, _, values = inspect.getargvalues(frame) 
    for i in args: 
     return [(i, values[i]) for i=0 and i=n] 

回答

3

还有一个办法让蟒蛇可变数量的函数参数(这就是所谓的var-positional)。然后他们结束列表:

def func(*args): # The trick here is the use of the star 
    if len(args) < 3: # In case needed, also protects against IndexError 
     raise TypeError("func takes at least 3 arguments") 
    return [args[0], args[-1]] 
+0

非常感谢。这就是我一直在寻找的东西。 – Eleanordum 2015-04-04 11:38:38

3

你正在推翻这一点。你已经有了第一个和最后的论点引用:

def func(a, b, c): 
    print [a, c] 
+0

我认为这太简单了。谢谢! – Eleanordum 2015-04-04 11:13:47

相关问题