0

我试图找出存在多少“用户名”。目前有两个,我可以循环users获得这个,但感觉很笨重。有没有办法获取用户中有多少个用户名?

open('file.yaml', 'r') as f:
  file = yaml.safe_load(f)

  # count number of usernames in user...?

文件.yaml:

host: "example.com"
timeout: 60

work:
-
  processes: 1
  users:
  -
    username: "me"
  -
    username: "notme"
4

1 回答 1

1

如果您想从特定结构中获取计数:

sum([len(x["users"]) for x in d["work"]])

对于一般解决方案,您可以执行以下操作:

f = open("test.yaml")
d = yaml.safe_load(f)

# d is now a dict - {'host': 'example.com', 'work': [{'processes': 1, 'users': [{'username': 'me'}, {'username': 'notme'}]}], 'timeout': 60}

def yaml_count(d, s):
    c = 0
    if isinstance(d, dict):
        for k, v in d.iteritems():
            if k == s: c += 1
            c += yaml_count(v, s)
    elif isinstance(d, list):
        for l in d:
            c += yaml_count(l, s) 
    return c

yaml_count(d, "username") # returns 2
于 2013-08-10T07:28:13.187 回答