Python:函数中的"多个"多个参数

Win*_*ags 3 python arguments function

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

此脚本查找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"
Run Code Online (Sandbox Code Playgroud)

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

如,比喻:

if find("string", "Wow!", source1, source2) is True:
    print "Succeed"
else:
    print "Fail"
Run Code Online (Sandbox Code Playgroud)

如何让脚本识别出什么是a word,什么应该是source?

Mar*_*ers 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
Run Code Online (Sandbox Code Playgroud)

现在您可以将其称为:

find("string", source1, source2)
Run Code Online (Sandbox Code Playgroud)

要么

find(("string1", "string2"), source1, source2)
Run Code Online (Sandbox Code Playgroud)

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