所以我必须编写一个函数,它接收dictionary作为输入参数,并返回输入dictionary的相反值,其中原始字典的值用作返回字典的键,而原始字典的键用作返回字典的值。在
例如,如果函数被调用为
reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})
那么我的功能应该回来了
^{pr2}$这是我的职责
def reverse_dictionary(input_dict):
d={}
def countEmpty(dictionario):
count=0
for k,v in dictionario.items():
if(len(dictionario[k])==0):
count+=1
return count
def removo(dicto, dicto2):
for k,v in dicto.items():
#v.sort()
if (len(dicto[k])!=0):
if v[-1] not in dicto2:
dicto2[v[-1].lower()]=[k.lower()]
else:
dicto2[v[-1]].append(k.lower())
dicto[k]=v[:-1]
while countEmpty(input_dict)<len(input_dict):
removo(input_dict,d)
for k,v in d.items():
v.sort()
return d
dicta={'astute': ['Smart', 'clever', 'talented'], 'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'talented': ['smart', 'keen', 'Bright'], 'smart': ['clever', 'bright', 'talented']}
print(reverse_dictionary(dicta))
这个程序最初起作用了。它颠倒了字典。但是字典中的值需要排序。 我用以下工具测试了该程序:
dicta={'astute': ['Smart', 'clever', 'talented'], 'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'talented': ['smart', 'keen', 'Bright'], 'smart': ['clever', 'bright', 'talented']}
它有时会返回:
{'keen': ['talented'], 'talented': ['astute', 'smart'], 'clever': ['astute', 'smart'], 'exact': ['accurate'], 'bright': ['smart', 'talented'], 'precise': ['accurate', 'exact'], 'smart': ['astute', 'talented']}
这是正确答案,但有时也会返回:
{'bright': ['smart', 'talented'], 'exact': ['accurate'], 'talented': ['astute', 'smart'], 'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'smart': ['astute'], 'keen': ['talented']}
它的“智能”键缺少“天才”值。即使我没有做任何改变代码。我知道python中的字典实际上没有任何顺序,但是值不应该是一致的吗?为什么会这样?在
您可以创建一个元组的排序列表,将每个值与其原始dict中的键关联起来,然后使用itertools.groupby,dict comprehension和list comprehesis合并输出:
^{1}$中间列表l:
^{pr2}$输出:
你得到的是未排序的输出,因为字典是按设计未排序的。以可预测的顺序查看键的唯一方法是使用
collections.OrderedDict
(dict替换),它只是按照插入的顺序显示它们。每次都会得到不同的输出,因为python的设计者作为一种防止拒绝服务攻击的安全措施,在密钥的存储和返回顺序上引入了一个非确定性的组件。在如果字典中的值列表已经排序,则只需在检索关键字时对其进行排序:
^{1}$或等效(因为元组首先按第一个元素排序):
^{pr2}$我已经能够重现你的错误,一个不一致的输出。你的算法可能有两个问题。在
items
返回项目的视图,而不是显式的iterable(请参见this question)。在您似乎可以使用以下行来“解决”这两个问题:
^{1}$这在我的测试中提供了一致、正确的输出。我对为什么这是有效的并不是很有信心,而且缺乏解释可能是关于为什么不应该在一个不断变化的对象开始迭代的陈述。在
有趣的是,这里有一个不同的愚蠢的解决方案:
^{pr2}$相关问题 更多 >
编程相关推荐