2015-08-22 48 views
3

我是一個Python新手,但我知道我可以允許在函數中使用*args可變數目的多個參數。Python:「多個」函數中的多個參數

這個腳本會查找word在任何數量的字符串*sources的:

def find(word, *sources): 
    for i in list(sources): 
     if word in i: 
      return True 

source1 = "This is a string" 
source2 = "This is Wow!" 

if find("string", source1, source2) is True: 
    print "Succeed" 

然而,就是它可以指定「多」多個參數(*args)在一個功能?在這種情況下,這將在多個*sources中尋找多個*words

如,比喻:

if find("string", "Wow!", source1, source2) is True: 
    print "Succeed" 
else: 
    print "Fail" 

我怎樣才能使腳本辨別什麼是打算成爲一個word,什麼是應該是一個source

+0

如果你有多個多個參數你會怎樣調用這個函數? python如何知道哪個值放入哪個值? –

回答

5

不,你不能,因爲你無法區分一種元素停止和另一種開始。

有你的第一個參數接受一個單一字符串或序列,而不是:

def find(words, *sources): 
    if isinstance(words, str): 
     words = [words] # make it a list 
    # Treat words as a sequence in the rest of the function 

現在,你可以把它無論是作爲:

find("string", source1, source2) 

find(("string1", "string2"), source1, source2) 

通過明確地傳遞序列,您可以將它與多個來源區分開來,因爲它本質上只是一個來源論點。

+1

@VigneshKalai:在這種情況下,通過將問題標記爲重複,選民可能會更有幫助。不過,我懷疑這是他們的動機。 –

+0

如果預計會有不止一種類型的論證,我的經驗告訴我完全避免使用'*'和'**'魔法。當你使用關鍵字參數時,它會變得雜亂,並且感覺不完全「一致」,就像在你的例子中那樣:單詞必須作爲迭代被傳遞,源作爲可變參數。編寫「def find(words,sources)」可能看起來並不那麼pythonic,但從長遠來看,一致性和清潔性打破了酷語法。 – bgusach

2

需要「多個多個來源」的通常解決方案是使*args成爲第一個倍數,第二個倍數是元組。

>>> def search(target, *sources): 
     for i, source in enumerate(sources): 
      if target in source: 
       print('Found %r in %r' % (i, source)) 
       return 
     print('Did not find %r' % target) 

你會發現這樣的API設計的整個Python的核心語言使用的其他例子:

>>> help(str.endswith) 
Help on method_descriptor: 

endswith(...) 
    S.endswith(suffix[, start[, end]]) -> bool 

    Return True if S ends with the specified suffix, False otherwise. 
    With optional start, test S beginning at that position. 
    With optional end, stop comparing S at that position. 
    suffix can also be a tuple of strings to try. 

>>> 'index.html'.endswith(('.xml', '.html', '.php'), 2) 
True   
    >>> search(10, (5, 7, 9), (6, 11, 15), (8, 10, 14), (13, 15, 17)) 
    Found 2 in (8, 10, 14) 

注意後綴可以是tuple of strings to try

+1

感謝您的支持! – Winterflags

+0

我不明白這是如何回答OP有效地希望能夠處理'* targets'和*'* sources'的問題。 – martineau