0

这与处理类似命令行的参数有关。

给定一个字符串列表,我想将这些字符串提取到具有附加功能的变量中,即最后一个变量列表接收任何剩余的列表元素作为列表的一部分,未提取的剩余部分,如下所示:

    command, target, operation, parameters = 
    some_function(["grant", "woody", "rights", "read", "write", "delete"])

执行后some_function,变量应具有以下值:

command = "grant"
target = "woody"
operation = "rights"
parameters = ["read", "write", "delete"]

如果必须,我会编写自己的函数,但我想知道 python 是否有一种严格的方法来做到这一点。

4

1 回答 1

3

使用扩展的可迭代解包

command, target, operation, *parameters = ["grant", "woody", "rights", "read", "write", "delete"]

print(command)
print(target)
print(operation)
print(parameters)

输出

grant
woody
rights
['read', 'write', 'delete']
于 2021-09-14T20:07:59.487 回答