实现group_by_owners字典

4mA*_*tro 1 python dictionary loops if-statement python-3.x

我成功尝试了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))
Run Code Online (Sandbox Code Playgroud)

输出:

{'Stan': ['Code.py'], 'Randy': ['Output.txt', 'Input.txt']} 
Run Code Online (Sandbox Code Playgroud)

zwe*_*wer 12

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']}
Run Code Online (Sandbox Code Playgroud)

你可以通过使用collections.defaultdictfor result和初始化它的所有键来进一步简化它list- 然后你甚至不需要创建一个新列表的杂技,如果它在添加之前还没有.


小智 7

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

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))
Run Code Online (Sandbox Code Playgroud)