[英]Not getting the desired output in python
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]}
作為輸出。 我該怎么辦?
像這樣附加后嘗試對其進行排序:
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
項目()¶
返回字典的(鍵,值)對列表的副本。
CPython 實現細節:鍵和值以非隨機的任意順序列出,因 Python 實現而異,並取決於字典的插入和刪除歷史。
這同樣適用於iteritems
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.