gpt4 book ai didi

python - 可选参数约束

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:12 25 4
gpt4 key购买 nike

框架:机器人,语言:Python-3.7.1 熟练程度:新手

我有以下核心方法,它在匹配时替换动态位置,并在我现有的自动化脚本中广泛使用。

 def querybuilder(self, str, symbol, *args):
count = str.count(symbol)
str = list(str)
i = 0
j = 0
if (count == (len(args))):
while (i < len(str)):
if (str[i] == symbol):
str[i] = args[j]
j = j + 1
i = i + 1
else:
return ("Number of passed arguments are either more or lesser than required.")
return ''.join(str)

如果像下面这样发送参数,这工作正常

def querybuilder("~test~123", "~", "foo","boo")

但是如果我想作为一个列表来代替可选参数发送,它会将每个列表/元组/数组作为一个参数,因此不会进入 if 条件。

例如:-

i = ["foo", "boo"] -- Optional argument consider it as ('foo, boo',)

显然,由于现有框架中广泛使用的影响,我无法对方法 (querybuilder) 进行任何更改。

我试图摆脱的东西:-

1, ", ".join("{}".format(a) for a in i,
2, tuple(i),
3, list(i),
4, numpy.array(i) part of import numpy

根据要求转换参数的任何可能的解决方案?

最佳答案

将您的列表作为 *['foo', 'boo']

def querybuilder(s, symbol, *args):
count = s.count(symbol)
st = list(s)
i = 0
j = 0
if (count == (len(args))):
while (i < len(st)):
if (st[i] == symbol):
st[i] = args[j]
j = j + 1
i = i + 1
else:
return ("Number of passed arguments are either more or lesser than required.")
return ''.join(st)

print(querybuilder("~test~123", "~", "foo","boo"))
# footestboo123
print(querybuilder("~test~123", "~", *["foo","boo"]))
# footestboo123

关于python - 可选参数约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56305697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com