簡體   English   中英

將值放入元組列表中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM