首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取YAML文件和访问列表

读取YAML文件和访问列表
EN

Stack Overflow用户
提问于 2018-04-13 16:04:45
回答 1查看 2K关注 0票数 1

我目前正在从.yml文件中读取数据。文件中的每个主条目都有以下部分:

代码语言:javascript
复制
- !
  name: Martial Focus
  prerequisites:
    tier1:
      any:
        Attribute:
        - Attribute1:§ 1
        - Attribute2:§ 1
        Feat:
        - Feat1
        Other:
        - Other Prerequisites
  cost:
  - 3
  description: |
    [...]
  effect: |
    [...]

我已经能够读取所有的数据,包括“先决条件”,但是这里我有一个特殊的问题:对于其他数据,我能够访问子列表的地方--它似乎与此不同:

"any:“部分是可选的,所以它也可以这样说

代码语言:javascript
复制
prerequisites:
    tier1:
      Attribute:
      - Attribute1:§ 1
      - Attribute2:§ 1
      Feat:
      - Feat1
      Other:
      - Other Prerequisites

读取.yml文件可将上述部分转换为

代码语言:javascript
复制
'prerequisites': {
  'tier1': {
    'any': {
      'Attribute': ['Attribute1:§ 1', 'Attribute2:§ 1'],
      'Feat': ['Feat1'],
      'Other': ['Other Prerequisites']
    }
  }
}

因此,在我的代码中,对于每一个"tierX",我都会检查它是否包含一个键"any:“

代码语言:javascript
复制
if 'any' in tier:
  # do the stuff to be done if 'any' exists
else:
  # do the stuff to be done if it doesn't

但这似乎从来都不是真的。因为“属性:”、“壮举:”和“其他:”也是可选的,我对if-否则语句中的那些语句也是这样做的,尽管对于那些没有其他语句的语句,它们也有相同的问题。下面你可以找到我正在使用的代码。自从我今天从蟒蛇开始的时候,它就不会是最漂亮的了,但我希望你能帮我:

代码语言:javascript
复制
        prerequisites = ""
        tierNum = 0
        for tier in data['prerequisites']:
            tierNum += 1
            thisTier = ""
            if 'any' in tier:
                print("'any' found!")
                content = tier['any']
                if 'Other' in content:
                    other = ""
                    for s2 in content['Other'][:-1]:
                        other += s2 + ", "
                    thisTier += "**" + other
                    if len(content['Other'][:-1]) == 0:
                        thisTier += str(content['Other'][-1:])
                    else:
                        thisTier += "or " + str(content['Other'][-1:])

                    if 'Attribute' in content:
                        attributes = ""
                        for s2 in content['Attribute'][:-1]:
                            attributes += s2 + ", "
                        if thisTier.length() == 0:
                            thisTier += "**" + attributes
                        else:
                            thisTier += ", or " + attributes
                        if len(content['Attribute'][:-1]) == 0:
                            thisTier += str(content['Attribute'][-1:])
                        else:
                            thisTier += "or " + str(content['Attribute'][-1:])

                    if 'Feat' in content:
                        feats = ""
                        for s2 in content['Feat'][:-1]:
                            feats += s2 + ", "
                        if thisTier.length() == 0:
                            thisTier += "**" + feats
                        else:
                            thisTier += ", or " + feats
                        if len(content['Feat'][:-1]) == 0:
                            thisTier += str(content['Feat'][-1:])
                        else:
                            thisTier += "or " + str(content['Feat'][-1:])

            else:
                content = tier
                if 'Other' in content:
                    other = ""
                    for s2 in content['Other'][:-1]:
                        other +=  s2 + ", "
                    thisTier += "**" + other
                    if len(content['Other'][:-1]) == 0:
                        thisTier += str(content['Other'][-1:])
                    else:
                        thisTier += "or " + str(content['Other'][-1:])

                if 'Attribute' in content:
                    attributes = ""
                    for s2 in content['Attribute'][:-1]:
                        attributes += s2 + ", "
                    thisTier += "**" + attributes
                    if len(content['Attribute'][:-1]) == 0:
                        thisTier += str(content['Attribute'][-1:])
                    else:
                        thisTier += "or " + str(content['Attribute'][-1:])

                if 'Feat' in content:
                    feats = ""
                    for s2 in content['Feat'][:-1]:
                        feats += s2 + ", "
                    thisTier += "**" + feats
                    if len(content['Feat'][:-1]) == 0:
                        thisTier += str(content['Feat'][-1:])
                    else:
                        thisTier += "or " + str(content['Feat'][-1:])

            prerequisites += "*Tier {0}:\n{1}\n".format(tierNum, thisTier)
        prerequisites = prerequisites[:-1]

我正在做一些像content['Feat'][:-1]这样的事情,以便获得除了最后一个元素之外的所有元素,这样我就可以在最后一个元素前面添加一个", or ",如果有多个元素的话。

编辑:我想要的输出应该如下所示:

代码语言:javascript
复制
Prerequisites:
*Tier 1:
**Attribute1 1, or Attribute2 1
**Feat1
**Other Prerequisites

如果没有的话

代码语言:javascript
复制
Prerequisites:
*Tier 1:
**Attribute1 1, or Attribute2 1, or Feat1, or Other Prerequisites

如果没有

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-13 16:31:29

您的问题是for tier in data["predicates"]在谓词字典的上迭代,因此后续if "any" in tier实际上计算了"any" in "tier1",这是导致始终为false的原因。

您想在这里测试的是"any" in data["predicates"]["tier1"]。在使用字典(即映射)时,您必须区分key及其对应的value

有趣的是,你已经为下一关做好了准备:

代码语言:javascript
复制
# ...
content = tier['any']
if 'Other' in content:
    other = ""
    for s2 in content['Other']:
       # ...

遍历字典的方法

代码语言:javascript
复制
d = {"key1":"value1", "key2":"value2", "key3":"value3"}
for key in d:
  print(key)
# prints key1, key2, key3
for key in d.keys():
  print(key)
# prints key1, key2, key3
for value in d.values():
  print(value)
# prints value1, value2, value3
for item in d.items():
  print(item)
# prints (key1,value1), (key2,value2), (key3,value3)
for key, value in d.items():
  print(key)
  print(value)
# prints key1, value1, key2, value2, key3, value3

参见python文档这里这里

由于您是Python新手,不知道什么是可能的,请允许我为您提供一个更优雅的解决方案,不需要所有重复的字符串操作:

代码语言:javascript
复制
import yaml


yamldata1 = r"""
- !
  name: Martial Focus
  prerequisites:
    tier1:
      any:
        Attribute:
        - Attribute1:§ 1
        - Attribute2:§ 1
        Feat:
        - Feat1
        Other:
        - Other Prerequisites
  cost:
  - 3
  description: |
    [...]
  effect: |
    [...]
"""
yamldata2 = r"""
- !
  name: Martial Focus
  prerequisites:
    tier1:
        Attribute:
        - Attribute1:§ 1
        - Attribute2:§ 1
        Feat:
        - Feat1
        Other:
        - Other Prerequisites
  cost:
  - 3
  description: |
    [...]
  effect: |
    [...]
"""


def process(data):
    output = ""
    for tier_name, tier in data['prerequisites'].items():
        output += f"* {tier_name}"
        if 'any' in tier:
            content = tier['any']
            prerequisites = content.get('Other', []) + content.get('Attribute', []) + content.get('Feat', [])
            if prerequisites:
                output += "\n** " + " or ".join(prerequisites)
        else:
            content = tier
            prerequisites = [content.get('Other', []), content.get('Attribute', []), content.get('Feat', [])]

            for subset in prerequisites:
                if subset:
                    output += "\n** " + " or ".join(subset)
    return output


data = yaml.load(yamldata1)[0]
print(process(data))
print('#'*10)
data = yaml.load(yamldata2)[0]
print(process(data))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49821100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档