【问题标题】:Python: "Multiple" multiple arguments in functionPython:函数中的“多个”多个参数
【发布时间】:2015-08-22 16:32:14
【问题描述】:

我是 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"

但是,是否可以在一个函数中指定 "multiple" 多个参数 (*args)?在这种情况下,这将在多个 *sources 中寻找多个 *words

形象地说:

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

我怎样才能让脚本辨别什么是word,什么应该是source

【问题讨论】:

  • 如果您有多个参数,您将如何调用该函数? python如何知道将哪个值放入哪个?

标签: python function arguments


【解决方案1】:

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

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

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)

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

【讨论】:

  • @VigneshKalai:在这种情况下,选民可以通过将问题标记为重复来提供更多帮助。然而,我怀疑那是他们的动机。
  • 在预期不止一种类型的论点的情况下,我的经验告诉我要完全避免 *** 魔术。当您使用关键字参数时,它会变得混乱,并且感觉不完全“一致”,就像在您的示例中一样:单词必须作为可迭代传递,源作为可变参数。写 def find(words, sources) 可能看起来不那么 Pythonic,但从长远来看,一致性和简洁性胜过很酷的语法。
【解决方案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)

注意后缀可以是tuple of strings to try

【讨论】:

  • 我看不出这如何回答这个问题,即 OP 有效地希望能够处理 *targets *sources
猜你喜欢
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多