我有以下YAML文件名爲input.yaml
:如何使用PyYAML讀取python元組?
cities:
1: [0,0]
2: [4,0]
3: [0,4]
4: [4,4]
5: [2,2]
6: [6,2]
highways:
- [1,2]
- [1,3]
- [1,5]
- [2,4]
- [3,4]
- [5,4]
start: 1
end: 4
我加載它使用PyYAML和打印結果如下:
import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
print(data)
結果是數據結構如下:
{ 'cities': { 1: [0, 0]
, 2: [4, 0]
, 3: [0, 4]
, 4: [4, 4]
, 5: [2, 2]
, 6: [6, 2]
}
, 'highways': [ [1, 2]
, [1, 3]
, [1, 5]
, [2, 4]
, [3, 4]
, [5, 4]
]
, 'start': 1
, 'end': 4
}
正如你所看到的,每個城市和高速公路都被列爲一個列表。但是,我希望他們能夠被表示爲一個元組。因此,我使用解析手動將它們轉換爲元組:
import yaml
f = open("input.yaml", "r")
data = yaml.load(f)
f.close()
data["cities"] = {k: tuple(v) for k, v in data["cities"].items()}
data["highways"] = [tuple(v) for v in data["highways"]]
print(data)
但是,這看起來像一個黑客。有什麼方法可以指示PyYAML直接將它們讀爲元組而不是列表?
帶標籤的IMO最大的問題是它們強迫你通過load()方法使用不安全的'Constructor',並且不能再通過'safe_load()'使用'SafeConstructor'。 – Anthon
事實上,我不認爲有更好的方法來完成我想要做的事情。 –