【问题标题】:Need a one liner to extract members of a python list to varaibles (applies to many languages)需要一个衬垫来将 python 列表的成员提取到变量中(适用于多种语言)
【发布时间】:2021-11-10 00:02:18
【问题描述】:

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

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

    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 是否有一种严格的方法。

【问题讨论】:

  • 查看拆包
  • 使用command, target, operation, *parameters = ["grant", "woody", "rights", "read", "write", "delete"]
  • 现在这就是我要说的!谢谢。

标签: python list variables extract one-liner


【解决方案1】:

使用extended iterable unpacking:

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

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

输出

grant
woody
rights
['read', 'write', 'delete']

【讨论】:

    猜你喜欢
    • 2022-10-04
    • 2012-09-11
    • 2011-02-22
    • 2017-11-10
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 2017-07-05
    相关资源
    最近更新 更多