实施 group_by_owners 字典

新手上路,请多包涵

我成功地尝试了 TestDome.com Fileowners 问题,想看看是否有人有建议来简化我的回答。在线 IDE 使用 Python 3.5.1。如果您正在尝试自己解决问题并且只是在寻找答案,那么这里有一个。据了解,我是一名 Python 专家,所以这花了我很长一段时间来进行大量修改。任何评论都会有所帮助,即使它是关于语法或一般清洁度的。谢谢!

实现一个 group_by_owners 函数:

接受包含每个文件名的文件所有者名称的字典。返回一个字典,其中包含每个所有者名称的文件名列表,顺序不限。例如,对于字典 {‘Input.txt’: ‘Randy’, ‘Code.py’: ‘Stan’, ‘Output.txt’: ‘Randy’} group_by_owners 函数应该返回 {‘Randy’: [‘Input. txt’, ‘Output.txt’], ‘Stan’: [‘Code.py’]}.

 class FileOwners:

@staticmethod
def group_by_owners(files):
    val = (list(files.values()))                    #get values from dict
    val = set(val)                                  #make values a set to remove duplicates
    val = list(val)                                 #make set a list so we can work with it
    keyst = (list(files.keys()))                    #get keys from dict
    result = {}                                     #creat empty dict for output
    for i in range(len(val)):                       #loop over values(owners)
        for j in range(len(keyst)):                 #loop over keys(files)
            if val[i]==list(files.values())[j]:     #boolean to pick out files for current owner loop
                dummylist = [keyst[j]]              #make string pulled from dict a list so we can add it to the output in the correct format
                if val[i] in result:                #if the owner is already in the output add the new file to the existing dictionary entry
                    result[val[i]].append(keyst[j]) #add the new file
                else:                               #if the owner is NOT already in the output make a new entry
                    result[val[i]] = dummylist      #make a new entry
    return result

files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}

print(FileOwners.group_by_owners(files))

输出:

 {'Stan': ['Code.py'], 'Randy': ['Output.txt', 'Input.txt']}

原文由 4mAstro 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 525
2 个回答

Holly molly,如此简单的事情有很多代码:

 def group_by_owners(files):
    result = {}
    for file, owner in files.items():  # use files.iteritems() on Python 2.x
        result[owner] = result.get(owner, []) + [file]  # you can use setdefault(), too
    return result

files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
}

print(group_by_owners(files))
# {'Stan': ['Code.py'], 'Randy': ['Output.txt', 'Input.txt']}

您可以进一步简化它,方法是使用 collections.defaultdict 用于 result 并将其所有键初始化为 list 然后您甚至不需要创建一个新列表,如果它在附加到它之前还不存在。

原文由 zwer 发布,翻译遵循 CC BY-SA 3.0 许可协议

我个人发现赞成的答案很难理解,而其他一些则有点笨重。这是我的版本:

 def group_by_owners(files):

ownerdict = {}

for key, value in files.items():
    if value in ownerdict:
        ownerdict[value].append(key)
    else:
        ownerdict[value] = [key]
return ownerdict

files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
}
print(group_by_owners(files))

原文由 Ruben 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏