我成功地尝试了 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 许可协议
Holly molly,如此简单的事情有很多代码:
您可以进一步简化它,方法是使用
collections.defaultdict
用于result
并将其所有键初始化为list
然后您甚至不需要创建一个新列表,如果它在附加到它之前还不存在。