首页 > 解决方案 > 获取列表中的所有元素,直到其结束或另一个参数 Python

问题描述

例如,我有一个命令需要很少的位置参数

send_dm -u def750 -n 15 -msg 世界你好!

它需要整个列表和索引参数

('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!')
def750 1 "Hello

使用此代码:

allowed_args = ["-u", "-n", "-msg"]    
index = args.index("-u") + 1
u = str(args[index])
index = args.index("-n") + 1
n = str(args[index])
index = args.index("-msg") + 1
msg = str(args[index])

我需要从一开始就采用 -msg 参数

  1. 新论点的开始
  2. 参数列表结束

所以如果我做这样的事情

send_dm -msg 世界你好!-u def750 -n 15

我仍然会得到: def750 1 Hello World!

现在我唯一得到的是 -msg 参数之后的第一个元素,我不知道该怎么做

标签: pythondiscord.py

解决方案


-也许尝试在每个参数的开头寻找

allowed_args = ["-u", "-n", "-msg"]
argumentDict = {
    "-u": "",
    "-n": "",
    "-msg": ""
}

currentArgument = ""
for argument in args:
    if argument.startswith("-"):
        if argument not in allowed_args:
            return # wrong argument given
        currentArgument = argument
    else:
        if argumentDict[currentArgument] != "": # add space when already something given
            argumentDict[currentArgument] += " "
        argumentDict[currentArgument] += argument

然后,您可以通过以下方式访问您的参数

argumentDict["-u"]
argumentDict["-n"]
argumentDict["-msg"]

的输出

print(argumentDict)

将会

{'-u': 'def750', '-n': '1', '-msg': 'Hello world!'}

推荐阅读