Python:函数中的“多个”多个参数
发布时间:2020-12-20 11:44:40 所属栏目:Python 来源:网络整理
导读:我是一个 Python新手,但我知道我可以使用* args在函数中允许可变数量的多个参数. 此脚本在任意数量的字符串*源中查找单词: def find(word,*sources): for i in list(sources): if word in i: return Truesource1 = "This is a string"source2 = "This is Wo
我是一个
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!",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",source2) 要么 find(("string1","string2"),source2) 通过明确地传递一个序列,您可以将它与多个源区分开来,因为它本质上只是一个参数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |