Python 按所有者词典实现组
我在TestDome.com文件所有者问题上做了一次成功的尝试,想看看是否有人对简化我的答案提出了建议。在线IDE使用Python 3.5.1。如果你想自己解决这个问题,只是想寻找答案,这里有一个。据我所知,我是一位Python专家,所以我花了相当长的时间进行了大量的修改。任何评论都会有帮助,即使是关于语法或一般清洁度的评论。谢谢 实施“按所有者分组”功能,该功能包括: 接受包含每个文件名的文件所有者名称的字典。 返回一个字典,其中包含每个所有者名称的文件名列表(按任意顺序)。 例如,对于字典{'Input.txt':'Randy','Code.py':'Stan','Output.txt':'Randy'},group_by_owners函数应该返回{'Randy':['Input.txt','Output.txt'],'Stan':['Code.py']}Python 按所有者词典实现组,python,python-3.x,loops,dictionary,if-statement,Python,Python 3.x,Loops,Dictionary,If Statement,我在TestDome.com文件所有者问题上做了一次成功的尝试,想看看是否有人对简化我的答案提出了建议。在线IDE使用Python 3.5.1。如果你想自己解决这个问题,只是想寻找答案,这里有一个。据我所知,我是一位Python专家,所以我花了相当长的时间进行了大量的修改。任何评论都会有帮助,即使是关于语法或一般清洁度的评论。谢谢 实施“按所有者分组”功能,该功能包括: 接受包含每个文件名的文件所有者名称的字典。 返回一个字典,其中包含每个所有者名称的文件名列表(按任意顺序)。 例如,对于字典{
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']}
霍莉·莫莉,对于这么简单的事情,有很多代码:
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']}
您可以通过使用
集合来进一步简化它。对于结果使用defaultdict
,并将其所有键初始化到列表——然后您甚至不需要在添加到列表之前创建一个新列表的技巧。我刚刚开始学习,我也是python的noob,但已经使用过了2.7. 所以别给我括号里的指纹了
我喜欢你的虚拟列表和附加的想法。类似的东西,但可能更干净一些:
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
owners=[]
filenames=files.keys()
for key in files:
if files[key] not in owners:
owners.append(files[key])
print owners
print filenames
result={}
for i in owners:
resultvalues=[]
for key in files:
if files[key]==i:
resultvalues.append(key)
print resultvalues
result[i]=resultvalues
print result
这里我要说的是容易理解的解决方案
owner = []
for i in dict1.keys():
if j not in owner:
owner.append(j)
results = {}
for i in owner:
result = []
for j in dict1.keys():
if dict1.get(j) == i:
result.append(j)
results[i] = result
print results
你们看起来都好多了,我花了3.5个小时的时间反复尝试,终于得到了答案,因为我对python还不熟悉,而且专注于思考能力很弱,多亏@zwer教授了一些新东西
dic={'apple':['green','red'], 'power': ['voltage'],'banana': ['green','red'],'current':['voltage'],'grass':['green'],'tiger':['lion']}
i = 0
adic = {}
while i < len(dic):
key = list(dic)[i]
for key2 in list(dic):
if key2 != key:
j = 0
while j < len(dic[key]):
if dic[key][j] in dic[key2]:
color = dic[key][j]
if dic[key][j] in adic:
if key not in adic[color]:
adic[dic[key][j]].append(key)
else:
mdic = {dic[key][j]: [key]}
adic.update(mdic)
else:
if dic[key][j] not in adic:
mdic = {dic[key][j]: [key]}
adic.update(mdic)
j = j + 1
i = i + 1
print(adic)
dic={'apple':['green','red'],'power':['voltage'],'banana':['green','red'],'current':['voltage'],'grass':['green'],'tiger':['lion']}
i=0
adic={}
而我
您必须将字典迭代到字典中,比较值并在新列表中追加键。在新字典中获取输出
class FileOwners:
@staticmethod
def group_by_owners(files):
new_dic = {}
for key,val in files.items():
key_list = []
for k,v in files.items():
if v == val:
#print(v)
key_list.append(k)
new_dic[v]= key_list
return new_dic
#print(new_dic)
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
print(FileOwners.group_by_owners(files))
我个人觉得这个上浮的答案很难理解,而其他一些答案有点笨重。以下是我的版本:
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))
我记录了所有人及其相关的文件名列表。为此,我首先创建了字典,将传递的字典文件的值作为键,空列表作为值。然后循环遍历文件
,并将文件
def group_by_owners(files):
return_dict = {}
owner_files = files.keys()
for f in owner_files:
return_dict[files[f]] = []
for f, n in files.items():
return_dict[n].append(f)
return return_dict
我昨天开始学习Python,在testdome上遇到了这个问题。以下是我的答案:
def group_by_owners(files):
f = files.values()
s = set(f)
newdict={}
fileOwners = list(s)
for owner in fileOwners:
l=[]
for file in files:
if owner == files[file]:
l.append(file)
newdict[owner]=l
return newdict
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
print(group_by_owners(files))
这是一些需要理解的复杂代码
但这是解决办法之一
files={
'input.txt':'randy',
'output.txt':'randy',
'code.py':'stan'
}
k=files.keys()
newfiles={value:key for key,value in files.items()}
emptylist=[]
for key in k:
if key not in newfiles.values():
missfile=key
valuetoadd=files[missfile]
emptylist.append(newfiles[valuetoadd])
emptylist.append(missfile)
newfiles[valuetoadd]=emptylist
print(newfiles)
这对我有用。我相信这会更有效和简单
# Input dictionary.
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
# Function to group the files.
def group_by_owners(files):
# Dictionary object to hold the result.
result = {}
for key, value in files.items():
if value not in result.keys():
# Insert the values into the resulting dictionary
# by interchanging the key, values.
result[value] = [key]
else:
# Append the othet file name if the owner is same.
result[value].append(key)
return result
print(group_by_owners(files))
以下是输出:
{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
以下是我对defaultdict的回答:
from collections import defaultdict
d = defaultdict(list)
def group_by_owners(files):
for k,v in files.items():
d[v].append(k)
return dict(d.items())
if __name__ == "__main__":
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
print(group_by_owners(files))
对代码的解释将有助于更好地回答问题,而这段代码可能会回答问题,提供有关如何和/或为什么解决问题的附加上下文将提高答案的长期价值。虽然这段代码片段可能是解决方案,但确实有助于提高您文章的质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。
{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
from collections import defaultdict
d = defaultdict(list)
def group_by_owners(files):
for k,v in files.items():
d[v].append(k)
return dict(d.items())
if __name__ == "__main__":
files = {
'Input.txt': 'Randy',
'Code.py': 'Stan',
'Output.txt': 'Randy'
}
print(group_by_owners(files))