在 Comprehension 中将列表内容转换为命名元素

Col*_*lin 0 python list-comprehension python-3.x

我什至很难描述这里发生了什么,但这段代码有效:

list_of_lists = [
  [1.1, 1.2],
  [2.1, 2.2]
]

for (first, second) in list_of_lists:
    print("%s %s" % (first, second))

# output:
# 1.1 1.2
# 2.1 2.2
Run Code Online (Sandbox Code Playgroud)

list_of_lists 的每个内部列表都将元素转换为变量名称“first”和“second”。

这个命名列表内容的过程叫什么?

另外,如果我想将结果转换为等效于的对象:

[
    {
        "first": 1.1,
        "second": 1.2
    },
    {
        "first": 2.1,
        "second": 2.2
    }
]
Run Code Online (Sandbox Code Playgroud)

我怎么能在列表理解中做到这一点?我正在尝试这样的事情,但我正在努力寻找表达我想要做的事情的语法,特别是关于 ???:

results = [??? for (first, second) in list_of_lists]
Run Code Online (Sandbox Code Playgroud)

我知道我可以做一些更详细的事情:

results = [{"first": l[0], "second": l[1]} for l in list_of_lists]
Run Code Online (Sandbox Code Playgroud)

...但我想以更简洁的形式来做,只使用名称而不是列表项索引。

小智 6

在迭代时从 list_of_lists 中解压元组。

results = [{"first": first, "second": second} for first, second in list_of_lists]
Run Code Online (Sandbox Code Playgroud)