gpt4 book ai didi

python - 一种插入多个参数的优雅方式

转载 作者:行者123 更新时间:2023-11-28 21:44:56 25 4
gpt4 key购买 nike

我有这本字典:

local_commands_dict = {
r"\b(listen)\b\s(\d+)": listen_for_connections
}

其中包含一个作为键匹配的正则表达式和一个作为值的方法变量。我正在使用以下代码将用户输入导航到字典中的命令:

for cmd in local_commands_dict:
regex = re.compile(cmd)
match = regex.match(data)
if match is not None:
if regex.groups == 1:
local_commands_dict[cmd]()
elif regex.groups == 2:
local_commands_dict[cmd](match.group(2))
elif regex.groups == 3:
local_commands_dict[cmd](match.group(2),match.group(3))
break

其中 data 是用户输入。有没有更好的方法在不同数量的参数之间导航?一定有,就是Python。

谢谢!

最佳答案

通常,您可以使用 * 传递可变数量的参数:

args = (1, 2)
func(*args) # Same as func(1, 2)

您可以调用 .groups() 来检索所有参数,并传递它们:

local_commands_dict[cmd](*match.groups())

如果你给你的组名字,那么这也有效:

def listen_for_connections(command, amount):
pass

local_commands_dict = {
r"\b(?P<command>listen)\b\s(?P<amount>\d+)": listen_for_connections
}

local_commands_dict[cmd](**match.groupdict())

现在 'command' 组的匹配作为 'command' 参数传递,'amount' 作为 'amount' 传递。这样,函数参数的顺序和正则表达式中组的顺序不需要相同,但名称必须相同。

关于python - 一种插入多个参数的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40216632/

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