为什么函数在列表中附加了错误的值?

iyr7buue  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(320)

我正在创建一个程序,其中包含一个包含部门和人员的词典,例如,此处的词典:

{"local": ["admin", "userA"],
 "public":  ["admin", "userB"],
 "administrator": ["admin"] }

然后返回一个字典,其中所有用户作为键,他们所在的部门列表作为值。
例如,先前给定列表的输出应为:

{"admin" : ["local", "public", "administrator"],
 "userA" : ["local"],
 "userB" : ["public"]}

以下是我的尝试:

def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary

    user_groups["admin"] = []
    user_groups["userA"] = []
    user_groups["userB"] = []

    for x in group_dictionary.values():
        # Now go through the users in the group
        for user in x:
            if user in group_dictionary["local"]:
                user_groups[user].append("local")
            elif user in group_dictionary["public"]:
                user_groups[user].append("public")
            elif user in group_dictionary["administrator"]:
                user_groups[user].append("administrator")

            # Now add the group to the the list of

# groups for this user, creating the entry

# in the dictionary if necessary

    return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))

但是,我得到了以下输出:

{'admin': ['local', 'local', 'local'],
 'userA': ['local'],
 'userB': ['public']}

此外,我还在代码的第5-7行定义函数中的用户。我该怎么做才能确保我的代码适用于任何给定的部门和用户?
例如,一个用户调用 "owner" 还有一个部门叫 "groupWorkspace" 不起作用,因为我没有在代码中定义它们。有人能解释一下如何解决这个问题吗?

d6kp6zgx

d6kp6zgx1#

使用 dict.setdefault 我们可以很容易地做到这一点:

groups = {"local": ["admin", "userA"],
          "public": ["admin", "userB"],
          "administrator": ["admin"]}

user_groups = {}
for group, users in groups.items():
    for user in users:
        user_groups.setdefault(user, []).append(group)

print(user_groups)

输出:

{'admin': ['local', 'public', 'administrator'],
 'userA': ['local'],
 'userB': ['public']}
rryofs0p

rryofs0p2#

这是一个非常糟糕的方法,但我希望你能理解你错在哪里。管理员总是在本地,所以 elif 对于public和administrator,将永远不会运行

def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary

    user_groups["admin"] = []
    user_groups["userA"] = []
    user_groups["userB"] = []

    for x in group_dictionary.values():
        # Now go through the users in the group
        for user in x:
            if user in group_dictionary["local"]:
                user_groups[user].append("local")
            if user in group_dictionary["public"]:
                user_groups[user].append("public")
            if user in group_dictionary["administrator"]:
                user_groups[user].append("administrator")

    for k,v in user_groups.items():
        user_groups[k] = list(set(v))

            # Now add the group to the the list of

# groups for this user, creating the entry

# in the dictionary if necessary

    return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))

# {'admin': ['administrator', 'local', 'public'], 'userA': ['local'], 'userB': ['public']}

一行只是为了好玩

d = {"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }

dict((k,[i[-1] for i in g]) for k, g in groupby(sorted(each_pair for k,v in d.items() for each_pair in sorted(map(lambda x: x[::-1], product([k],v)))), key=lambda x: x[0]))
50pmv0ei

50pmv0ei3#

我不认为这是“最佳”或最有效的解决方案。不过,我确实希望逻辑清晰,易于理解。

  • 请注意:我故意使用糟糕的变量名。希望鼓励“任何人”将其作为示例或理解其逻辑,并在项目中自行实现。使您不太可能在不完全理解甚至编辑此示例的情况下简单地复制+粘贴*

以下代码的结果是:

{ 'admin': ['local', 'public', 'administrator'], 
  'userA': ['local'], 
  'userB': ['public'] }

最后,如果您的输入数据不是唯一的,则执行重构并可能删除重复项的代码。

input = {
"local": ["admin", "userA"],
"public":  ["admin", "userB"],
"administrator": ["admin"]
}

def group_flip(input):
    # container for the result { user: [groups...], ...} structured result
    # this will be built up while iterating over the input
    user_groups = {}

    for g, us in input.items():
        # for each user in group
        for u in us:
            # we need to add it to the user_groups
            if not u in user_groups.keys():
                user_groups[u] = [g]
                continue

            # if not in list, add it
            if not g in user_groups[u]:
                user_groups[u].append(g)

    print(user_groups)
    return user_groups

if __name__ == '__main__':
    group_flip(input)

相关问题