python多个函数_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)

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

标签:python,function,arguments

来源: https://codeday.me/bug/20190727/1557860.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值