Python中函数的“多重”多个参数

3

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

此脚本在任意数量的字符串*sources中查找一个word

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"

我该如何让脚本区分哪些是单词,哪些是源代码


如果您有多个参数,您将如何调用函数?Python 如何知道将哪个值放在哪个参数中? - Anand S Kumar
2个回答

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:在这种情况下,投票者可以通过将问题标记为重复来提供更多帮助。然而,我怀疑这不是他们的动机。 - Martijn Pieters
当需要期望多种类型的参数时,我的经验告诉我要完全避免使用 *** 魔法。当您使用关键字参数时,它会变得混乱,并且不完全感觉“一致”,就像您的示例中:单词必须作为可迭代对象传递,源作为可变参数传递。编写 def find(words, sources) 可能看起来不太符合 Python 的风格,但从长远来看,一致性和清晰度胜过酷炫的语法。 - 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)

您会在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)

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

我看不出这如何回答问题,即 OP 实际上希望能够处理 *targets*sources - martineau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接