python - 将列表内容转换为可理解的命名元素
问题描述
我什至很难描述这里发生了什么,但这段代码有效:
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]
...但我想以更简洁的形式来做,只使用名称而不是列表项索引。
解决方案
迭代时从 list_of_lists 解压缩元组。
results = [{"first": first, "second": second} for first, second in list_of_lists]
推荐阅读
- jupyter-notebook - Jupyter Notebooks 中的 spacy 问题
- scala - 如何解决 spark read hive orc file meet 错误
- javascript - 导入函数时的 jest、jsdom 和文档对象
- python - df.to_markdown,ValueError:无法将字符串转换为浮点数:'1,000'。使用 disable_numparse=True 禁用数字解析
- algorithm - 算法 - 将水倒入瓶中
- node.js - fs.unlinkSync 抛出“不允许操作”错误,但仍然可以工作
- php - 如何从三个数据库表中进行嵌套循环?
- karate - 发送请求时,空手道会更新 Multipart Content-Type 标头
- evosuite - Evosuite:错误 TestSuiteGenerator 全栈:java.lang.IllegalArgumentException:null
- reactjs - 如何使用 joi 模式在反应 js 中进行密码验证?