【问题标题】:Get values into list of tuples将值获取到元组列表中
【发布时间】:2021-10-26 10:11:15
【问题描述】:

我有以下由 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")

【问题讨论】:

  • 元素的顺序应该保持不变。
  • 你试过什么,你卡在哪里了?您也肯定不会从yamldecode 获得= 的价值......?!或者我们在这里不是在谈论python[tuple(i.values()) for i in lst] 怎么样?

标签: python list yaml terraform tuples


【解决方案1】:

您可以使用 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)

【讨论】:

    【解决方案2】:

    如果顺序很重要,您可以执行以下操作:

    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",
      ],
    ]
    

    【讨论】:

      【解决方案3】:

      根据您的问题,不清楚您是在问如何用 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 将首先构造一个元组的元组(因为[] 括号构造元组)然后将 outer 元组转换为带有tolist 的列表.因此,如果写成 Terraform's type constraint syntaxlist_of_tuples 的最终类型将如下所示:

      list(tuple([string, number, string]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 2018-08-27
        • 2016-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-11
        相关资源
        最近更新 更多