[英]Get values into list of tuples
我有以下由 yamldecode(file("myfile.yaml")) 生成的结构,我使用 Terraform。
[
{
"name" = "A"
"number" = "1"
"description" = "Bla"
},
{
"name" = "B"
"number" = "2"
"description" = "Bla"
},
]
初始 yaml 看起来像:
test:
- name: "A"
number: '1'
description: "Bla"
- name: "B"
number: '2'
description: "Bla"
我需要从元组列表中的所有地图中获取值。 请指教
预期结果:
("A", 1, "Bla"), ("B", 2, "Bla")
您可以使用 pyyaml 库将 YAML 文件加载为 dict 并遍历数据。
使用pip install pyyaml 安装 pyyaml
import yaml
with open("test.yaml", "r") as stream:
data_list_dict = yaml.safe_load(stream)
output_list = []
for data_dict in data_list_dict['test']:
output_list.append(tuple(data_dict.values()))
print(output_list)
输出:
[('1', 'Bla', 'A'), ('2', 'Bla', 'B')]
或者
import yaml
with open("test.yaml", "r") as stream:
data_list_dict = yaml.safe_load(stream)
output_list = [tuple(data_dict.values()) for data_dict in data_list_dict['test']]
print(output_list)
如果顺序很重要,您可以执行以下操作:
locals {
test = [
{
"name" = "A"
"number" = "1"
"description" = "Bla"
},
{
"name" = "B"
"number" = "2"
"description" = "Bla"
},
]
list_of_lists = [for a_map in local.test:
[a_map["name"], a_map["number"], a_map["description"]]]
}
这使:
[
[
"A",
"1",
"Bla",
],
[
"B",
"2",
"Bla",
],
]
从您的问题来看,不清楚您是在询问如何用 Terraform 语言或 Python 解决这个问题——您只在问题正文中提到了 Terraform,但您将其标记为“python”并使用 Python 语法来显示元组。
其他人已经展示了如何在 Python 中执行此操作,因此以防万一您询问 Terraform,以下是 Terraform 的等效项:
locals {
input = [
{
"name" = "A"
"number" = "1"
"description" = "Bla"
},
{
"name" = "B"
"number" = "2"
"description" = "Bla"
},
]
list_of_tuples = tolist([
for e in local.input : [e.name, e.number, e.description]
])
}
Terraform 中的元组是一种序列类型,其长度是固定的,每个元素都可以有自己指定的类型。 它是对象的序列等价物,而列表对应于地图。
在评估上面的list_of_tuples
表达式时,Terraform 将首先构造一个元组元组(因为[]
括号构造元组),然后将外部元组转换为带有tolist
的列表。 因此,如果使用Terraform 的类型约束语法编写,则list_of_tuples
的最终类型将如下所示:
list(tuple([string, number, string]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.