2012-06-14 139 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