簡體   English   中英

Python yml 配置文件

[英]Python yml config file

我正在使用 python3 / 版本 3.6.9 並使用 yml 配置文件:

with open("config.yml", "r") as ymlfile:
    cfg = yaml.load(ymlfile)

for section in cfg:
    print(section)

直到現在我只能得到這個 Output:寶馬,雪佛蘭,梅賽德斯

我想遍歷配置文件的所有元素並檢查價格、座位、年份的單個值,例如可以單獨過濾最多座位、最高價格……。 並且以后必須可以在不更改代碼的情況下擴展配置文件。

感謝您的每一個幫助

Cars:
      BMW:
            Price: 420
            Seats: 4
            Year: 2022
      Chevy:
            Price: 423
            Seats: 5
            Year: 1975
      Mercedes:
            Price: 424
            Seats: 6
            Year: 2000

要獲得大多數座位,您可以使用問題中提供的 Yaml 的最高價格(只要Cars的結構保持不變,此腳本就可以使用):

import yaml

with open("config.yml", "r") as ymlfile:
    cfg = yaml.safe_load(ymlfile)

most_seats = max(cfg["Cars"], key=lambda car: cfg["Cars"][car]["Seats"])
highest_price = max(cfg["Cars"], key=lambda car: cfg["Cars"][car]["Price"])
oldest = min(cfg["Cars"], key=lambda car: cfg["Cars"][car]["Year"])

print("Most seats =", most_seats)
print("Highest price =", highest_price)
print("Oldest =", oldest)
Most seats = Mercedes
Highest price = Mercedes
Newest = Chevy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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