def dict_invert(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
result = {}
for k, v in d.iteritems():
result.setdefault(v, []).append(k)
return result
在上述程序中,所有输出都是正确的
a
Out[82]: {2: 6, 4: 6, 6: 6, 8: 6}
dict_invert(a)
Out[83]: {6: [8, 2, 4, 6]}
但根据我的任务,我需要{6: [2, 4, 6, 8]}
作为输出。
我该怎么办?
答案 0 :(得分:1)
尝试在追加之后对其进行排序:
def dict_invert(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
result = {}
for k, v in d.iteritems():
result.setdefault(v, []).append(k)
result[v].sort()
return result
<强>更新强>
效率很好,因为python算法Timsort适用于排序已排序的数据。
如果您希望提高效率,可以使用bisect
:
import bisect
def dict_invert(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
result = {}
for k, v in d.iteritems():
bisect.insort(result.setdefault(v, []), k)
return result
由于数据并不庞大且没有任何复杂的自定义相等运算符(这是一个int比较),我相信你几乎看不出差异。
将dict重新创建为排序的dict虽然会浪费空间和CPU时间,因此不太建议。
更新2:
基准测试代码:
import bisect
import timeit
d = {2: "6", 4: "6", 6: "6", 8:"6"}
def dict_invert(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
result = {}
for k, v in d.iteritems():
bisect.insort(result.setdefault(v, []), k)
return result
def dict_invert2(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
result = {}
for k, v in d.iteritems():
result.setdefault(v, []).append(k)
result[v].sort()
return result
def dict_invert3(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
result = {}
for k, v in d.iteritems():
result.setdefault(v, []).append(k)
return {k: sorted(v) for k, v in result.iteritems()}
print(timeit.timeit("dict_invert(d)", setup="from __main__ import dict_invert, d"))
print(timeit.timeit("dict_invert2(d)", setup="from __main__ import dict_invert2, d"))
print(timeit.timeit("dict_invert3(d)", setup="from __main__ import dict_invert3, d"))
python 2的输出:
2.4553718788
2.59005746839
2.88147985275
python 3的输出(将iteritems()
更改为items()
):
2.56672796628521
2.999647860343478
3.4022091183182583
答案 1 :(得分:0)
项()¶
返回字典的(键,值)对列表的副本。
CPython实现细节:键和值以非随机的任意顺序列出,在Python实现中各不相同,并且取决于字典的插入和删除历史。
同样适用于iteritems