0

「ユーザー名」がいくつ存在するかを調べようとしています。現在は 2 つあり、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 に答える