python - 如何迭代 YAML 文件以给出 PYTHON 中不同列表中项目的所有可能组合

标签 python yaml combinations pyyaml parser-combinators

我有一个包含这样序列的 YAML 文档

---
One: 
 - a
 - b
 - c
Two:
 - d
 - e
Three:
 - f
 - g
 - h 
 - i

我需要每次从每个列表中获取元素的所有可能组合,列表中的每个实例一个元素,并且必须使用所有列表。

我需要用Python来做到这一点。

到目前为止,我可以使用以下方式打印 YAML 文件:

#!/usr/bin/env python

import yaml

with open("parameters.yaml", 'r') as stream:
    try:
        print(yaml.load(stream))
    except yaml.YAMLError as exc:
        print(exc)

最佳答案

使用 itertools 的解决方案:

import itertools
import yaml

with open('parameters.yaml', 'r') as stream:
    try:
        inputdict = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)

total_list = [inputdict[key] for key in inputdict]
combinations = list(itertools.product(*total_list))
print(combinations)

输出:

[('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'), ('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'), ('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'), ('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i'), ('c', 'd', 'f'), ('c', 'd', 'g'), ('c', 'd', 'h'), ('c', 'd', 'i'), ('c', 'e', 'f'), ('c', 'e', 'g'), ('c', 'e', 'h'), ('c', 'e', 'i')]

关于python - 如何迭代 YAML 文件以给出 PYTHON 中不同列表中项目的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49993578/

相关文章:

javascript - 密码锁游戏 (JavaScript)

python - 如何在 python 中高效地多线程或多进程处理大型 itertools.combinations?

python - 如何使用 argparse 读取命令行的剩余部分?

laravel - 如何在laravel中读取yaml文件?

docker - 如何将字典以及列表成员添加到键?

python - 从组合列表中选择对的最佳策略

python - 无法从 read_csv 索引 Pandas 数据框中的日期

php - 从 Laravel 4 Controller 执行 Python 脚本

python - 为什么 PyObjC 文档如此糟糕?

javascript - 最不同的数据交换格式?