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

我是一个
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)

要么

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

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

点赞