获取列表中的所有元素,直到其结束或另一个参数

2024-04-20 03:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一个命令,它只接受几个非位置参数

send_dm -u def750 -n 15 -msg Hello world!

它接受整个列表和索引参数

('-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 Hello world! -u def750 -n 15

我仍然会得到: 世界你好

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


Tags: 代码命令sendhello列表world参数index
3条回答

有很多方法可以做到这一点。一种方法是循环参数并根据标志的状态追加参数,尽管这会非常冗长

另一种方法是使用itertools.groupby根据后续元素是否以“-”开头对其进行分组,并使用itertools.filterfalse过滤掉带破折号前缀的条目:

import itertools as it

DASH = '-'

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

parsedargs = it.filterfalse(lambda x: x[0],
                    it.groupby(args,
                        lambda y: y.startswith(DASH)))

或;立即将其放入字典,并过滤掉不允许的参数:

import itertools as it

DASH = '-'
allowed_args = ('-u','-n','-msg')
args = ('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!',
        '-not-allowed', 'asdf', 'qwerty')

argdict = {
    k: list(v[1])
    for k, v in zip(
        [entry for entry in args if entry.startswith(DASH)],
        it.filterfalse(lambda x: x[0],
                       it.groupby(args,
                                  lambda y: y.startswith(DASH)))
        )
    if k in allowed_args
   }

print(argdict)

导致:

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

但它的可读性不强

或者更简单、更可扩展、更可读;使用标准库中的argparse,因为它是为此目的而构建的,并且提供了更多的功能。还有一些第三方库,可以方便地为您的程序构建CLI

也许可以尝试在每个参数的开头查找-

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!'}

我不确定您是否正在寻找,但您可以尝试:

inp = ('-u', 'def750', '-n', '1', '-msg', 'Hello', 'world!')
allowed_args = ["-u", "-n", "-msg"] 
dic = {}
current_key = None
for el in inp:
    if el in allowed_args:
        current_key = el
        dic[current_key] = []
    else:
        dic[current_key].append(el)
    
for key, val in dic.items():
    dic[key] = " ".join(val)

print(dic)

输出:

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

相关问题 更多 >