简体   繁体   English

在Python中从yaml文件动态生成数组元素

[英]Dynamically generate array elements from yaml file in Python

Given the following yaml file stored in my_yaml that contains varying sets of dictionary keys and/or class variables (denoted by self._*): 给定存储在my_yaml中的以下yaml文件,其中包含各种字典键和/或类变量集(由self ._ *表示):

config1.json:
- [[foo, bar], [hello, world]]
config2.json:
- [[foo], [self._hi]]

From the json file, I want to populate a new list of tuples. 从json文件,我想填充一个新的元组列表。 The items in each tuple are determined by looking up dict keys in this yaml file. 每个元组中的项目都是通过在此yaml文件中查找字典键来确定的。

So if I iterate through a dictionary called config1.json , and I have an empty list called config_list , I want to do something like: 因此,如果我遍历一个名为config1.json的字典,并且有一个名为config_list的空列表,我想执行以下操作:

config_list.append(tuple[i['foo']['bar],i['hello']['world']])

But if it were config2.json , I want to do something like: 但是,如果它是config2.json ,我想做类似的事情:

config_list.append(tuple[i['foo'],self._hi])

I can do this in a less dynamic way: 我可以用一种不太动态的方式做到这一点:

for i in my_yaml['config1.json'][0]:
    config_list.append(tuple([ i[my_yaml[asset][0][0]][my_yaml[asset][0][1]],i[my_yaml[asset][1][0]][my_yaml[asset][1][1]]]))

or: 要么:

for i in my_yaml['config2.json'][0]:
    config_list.append(tuple([ i[my_yaml[asset][0][0]],i[my_yaml[asset][1][0]]]))

Instead I would like to dynamically generate the contents of config_list 相反,我想动态生成config_list的内容

Any ideas or alternatives would be greatly appreciated. 任何想法或选择将不胜感激。

I think you are bit confusing things, first of all because you are referring to a file in "From the json [ sic ] file" and there is no JSON file mentioned anywhere in the question. 我认为您有点困惑,首先是因为您是指“来自json [ sic ]文件”中的文件,而且问题中的任何地方都没有提到JSON文件。 There are mapping keys that look like filenames for JSON files, so I hope we can assume you mean "From the value associated with the mapping key that ends in the string .json ". 有些映射键看起来像JSON文件的文件名,所以我希望我们可以假设您的意思是“来自与以字符串.json结尾的映射键关联的值”。

The other confusing thing is that you obfuscate the fact that you want tuples but load list nested in list nested in lists from you YAML document. 另一个令人困惑的事情是,您混淆了想要元组但从YAML文档加载嵌套在列表中的列表的事实。 If you want tuples, it is much more clear to specify them in your YAML document: 如果需要元组,则在YAML文档中指定元组会更加清楚:

config1.json:
- !!python/tuple [[foo, bar], [hello, world]]
config2.json:
- !!python/tuple [[foo], [self._hi]]

So you can do: 因此,您可以执行以下操作:

import sys
import ruamel.yaml


yaml = ruamel.yaml.YAML(typ='unsafe')
with open('my.yaml') as fp:
    my_yaml = yaml.load(fp)

for key in my_yaml:
    for idx, elem in enumerate(my_yaml[key]):
        print('{}[{}] -> {}'.format(key, idx, my_yaml[key][idx]))

which directly gives you the tuples you seem to want instead of lists you need to process: 它直接为您提供您似乎想要的元组,而不是您需要处理的列表:

config1.json[0] -> (['foo', 'bar'], ['hello', 'world'])
config2.json[0] -> (['foo'], ['self._hi'])

In your question you hard code access to the first and only element of the sequence that are the values for the root level mapping. 在您的问题中,您硬编码访问序列的第一个也是唯一的元素,它们是根级别映射的值。 This forces you to use the final [0] in your for loop. 这迫使您在for循环中使用最后的[0] I assume you are going to have multiple elements in those sequences, but for a good question you should leave that out, as it is irrelevant for the question on how to get the tuples, and thereby only obfuscating things. 我假设您将在这些序列中包含多个元素,但是对于一个好问题,您应该将其排除在外,因为这与如何获取元组并因此仅使事物混淆的问题无关。

Please note that you need to keep control over your input, as using typ='unsafe' is, you guessed, unsafe. 请注意,您需要保持对输入的控制,因为您猜到使用typ='unsafe'是不安全的。 If you cannot guarantee that use typ='safe' and register and use the tag !tuple . 如果您不能保证使用typ='safe'并注册并使用标签!tuple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM