2012-06-14 138 views
2

我知道这个作品非常好:传递两个变量参数列表

def locations(city, *other_cities): 
    print(city, other_cities) 

现在我需要两个变量参数列表,像

def myfunction(type, id, *arg1, *arg2): 
    # do somethong 
    other_function(arg1) 

    #do something 
    other_function2(*arg2) 

但是Python中不允许使用两次

+4

你可以举一个例子来说明你希望如何调用这个函数吗? –

+5

Python如何知道参数是否应该在'arg1'或'arg2'中,如果两者都是可变的? –

回答

10

这是不可能的,因为*arg从该位置捕获所有位置参数。所以根据定义,第二个*args2将永远是空的。

一个简单的解决办法是通过两个元:

def myfunction(type, id, args1, args2): 
    other_function(args1) 
    other_function2(args2) 

,并调用它像这样:

myfunction(type, id, (1,2,3), (4,5,6)) 

如果这两个函数期望位置参数,而不是一个单独的参数,你会打电话他们是这样的:

def myfunction(type, id, args1, args2): 
    other_function(*arg1) 
    other_function2(*arg2) 

这样做的好处是可以使用任何在调用myfunction时可迭代,甚至是一个生成器,因为被调用的函数永远不会与传入的迭代进行接触。


如果你真的想使用两个可变参数列表,你需要某种分隔符。下面的代码使用None作为分隔符:

import itertools 
def myfunction(type, id, *args): 
    args = iter(args) 
    args1 = itertools.takeuntil(lambda x: x is not None, args) 
    args2 = itertools.dropwhile(lambda x: x is None, args) 
    other_function(args1) 
    other_function2(args2) 

它会像这样使用:

myfunction(type, id, 1,2,3, None, 4,5,6) 
+0

好的,我会试试。 –

+1

是的,只要'other_function'不依赖于特定的行为例如任何iterable就可以。一个列表或一个元组。 – ThiefMaster

1

您可以使用两个字典来代替。

+1

s/dictionaries /列表或元组/。数字将用于kwargs,但他使用posargs – ThiefMaster

+1

@ThiefMaster我不是在谈论**魔术,而是仅仅使用带参数的字典。我不知道为什么作者需要通过两个posargs列表 – Ribtoks