首页 > 解决方案 > 将列表内容转换为可理解的命名元素

问题描述

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

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

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

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

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

[
    {
        "first": 1.1,
        "second": 1.2
    },
    {
        "first": 2.1,
        "second": 2.2
    }
]

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

results = [??? for (first, second) in list_of_lists]

我知道我可以做一些更冗长的事情:

results = [{"first": l[0], "second": l[1]} for l in list_of_lists]

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

标签: pythonpython-3.xlist-comprehension

解决方案


迭代时从 list_of_lists 解压缩元组。

results = [{"first": first, "second": second} for first, second in list_of_lists]

推荐阅读