V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
css3
V2EX  ›  程序员

小弟遇到个 Python 里边的数据转换问题,有大佬帮忙解答一下吗?

  •  
  •   css3 · 2020-06-30 23:22:31 +08:00 · 1527 次点击
    这是一个创建于 1388 天前的主题,其中的信息可能已经有所发展或是发生改变。
    • 需求: 把一个 yaml 文件里边的一个节点的数据,分别转化成 tuple,最终用一个 list 来装 (用来给 pytest 做参数化)
    # case.yaml
    test_datas:
    
      - "输入正确的用户名 1"
      - username: test1
        password: 123456
      - expect_msg: success
    
    
      - "输入错误的用户名"
      - username: test2
        password: 123456
      - expect_msg: failed
    
    
      - "输入正确的用户名 2"
      - username: test3
        password: 123456
      - expect_msg: success
    
    
    
    • 期待转化的结果:
    test_datas = [
        ("输入正确的用户名 1", {"username": "test1", "password": "123456"}, {"expect_msg": "success"}),
        ("输入错误的用户名", {"username": "test2", "password": "123456"}, {"expect_msg": "failed"}),
        ("输入正确的用户名 2", {"username": "test3", "password": "123456"}, {"expect_msg": "success"}),
    ]
    
    • 然后我自己的读取 yaml 代码(就读了一个 yaml, 啥都没干,因为不会😥):
    import yaml
    
    
    def load_yaml(file_path):
        with open(file_path, encoding='utf-8') as f:
            data = yaml.safe_load(f)
        return data # 这里实在不知道怎么处理了😭,求大佬帮忙
    
    
    if __name__ == '__main__':
    	load_yaml("case.yaml")
    
    3 条回复    2020-07-01 03:12:47 +08:00
    QingchuanZhang
        1
    QingchuanZhang  
       2020-06-30 23:41:20 +08:00
    ```python3
    def load_yaml(file_path):
    with open(file_path, encoding='utf-8') as f:
    data = yaml.safe_load(f)
    record_len = 3

    for records in data.values():
    res = []
    for i in range(0, len(records), record_len):
    res.append(tuple(records[i:i + record_len]))
    return res
    ```
    QingchuanZhang
        2
    QingchuanZhang  
       2020-06-30 23:43:14 +08:00
    Cy86
        3
    Cy86  
       2020-07-01 03:12:47 +08:00
    test_datas:
    -
    - "输入正确的用户名 1"
    - username: test1
    password: 123456
    - expect_msg: success
    -
    - "输入错误的用户名"
    - username: test2
    password: 123456
    - expect_msg: failed
    -
    - "输入正确的用户名 2"
    - username: test3
    password: 123456
    - expect_msg: success

    我改成这样输出比较接近你要的格式, 但需要修改 YAML 格式
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4514 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 726ms · UTC 10:05 · PVG 18:05 · LAX 03:05 · JFK 06:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.