【发布时间】:2017-05-24 22:53:21
【问题描述】:
我对 TestDome.com Fileowners 问题进行了成功尝试,并想看看是否有人有建议来简化我的答案。在线 IDE 使用 Python 3.5.1。如果您想自己解决问题并且只是在寻找答案,这里有一个。众所周知,我是一名 Python 专家,所以这花了我很长一段时间来制作大量的修补程序。即使关于语法或一般清洁度,任何 cmets 都会有所帮助。谢谢!
实现一个 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']}
【问题讨论】:
标签: python python-3.x loops dictionary if-statement