Python 巨蟒:“;“多重”;函数中的多个参数

Python 巨蟒:“;“多重”;函数中的多个参数,python,function,arguments,Python,Function,Arguments,我是Python新手,但我知道我可以使用*args在函数中允许可变数量的多个参数 此脚本在任意数量的字符串*源中查找单词: 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, sourc

我是Python新手,但我知道我可以使用
*args
在函数中允许可变数量的多个参数

此脚本在任意数量的字符串
*源中查找
单词

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
)?在这种情况下,将在多个
*源中查找多个
*单词

例如,比喻地说:

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

我如何让脚本辨别什么是单词,什么是源代码?

不,你不能,因为你不能区分一种元素在哪里停止,另一种元素在哪里开始

让第一个参数接受单个字符串或序列,而不是:

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)


通过显式传递序列,您可以将其与多个源区分开,因为它本质上只是一个参数。

需要“多个源”的通常解决方案是将
*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)
您将在Python核心语言中找到此类API设计的其他示例:

>>> 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)

请注意,后缀可以是要尝试的字符串的
元组

如果您有多个参数,您将如何调用该函数?python怎么知道应该在哪个问题上输入哪个值?@VigneshKalai:在这种情况下,投票人可以通过将问题标记为重复问题来提供更多帮助。然而,我怀疑这是他们的动机。在不止一种类型的争论中,我的经验告诉我要完全避免
*
**
魔术。当您使用关键字参数时,它会变得混乱,并且感觉不完全“一致”,比如在您的示例中:单词必须作为iterable传递,源必须作为varargs传递。写
def find(words,sources)
看起来可能不太像python,但从长远来看,一致性和干净性胜过了酷的语法。我看不出这是如何回答OP想要有效地处理
*目标
*源
的问题的。
>>> 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)