Skip to main content
 首页 » 编程设计

python之实现 group_by_owners 字典

2025年05月04日10davidwang456

<分区>

我成功地尝试了 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']}