2010-11-03 38 views

回答

3
def your_function(*args): 
    # 'args' is now a list that contains all of the arguments 
    ...do stuff... 

input_args = user_string.split() 
your_function(*input_args) # Convert a list into the arguments to a function 

http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists

當然,如果你是一個設計功能,你可以只設計,它接受一個列表作爲一個參數,而不是需要單獨的參數。

1

最簡單的方式,使用str.split和論證拆包:

f(*the_input.split(' ')) 

然而,這將不執行任何轉換(所有參數仍然是字符串)和分有幾個注意事項(如'1,,2'.split(',') == ['1', '', '2'];參考文檔)。

+3

在絕大多數人寫'.split('')'的情況下,他們真正應該寫的是'.split()'。 – Amber 2010-11-03 19:58:09

+1

你設定的例子不是一個警告,它只是合乎邏輯! (因爲它在逗號分割) – Joschua 2010-11-03 19:58:45

1

有幾個選項。您可以進行功能拍攝的參數列表:

def fn(arg_list): 
    #process 

fn(["Here", "are", "some", "args"]) #note that this is being passed as a single list parameter 

或者你可以在任意參數列表收集的參數:

def fn(*arg_tuple): 
    #process 

fn("Here", "are", "some", "args") #this is being passed as four separate string parameters 

在這兩種情況下,arg_listarg_tuple將是幾乎相同的,唯一不同的是一個是列表,另一個是元組:["Here, "are", "some", "args"]("Here", "are", "some", "args")

相關問題