defsbv0(adict,reverse
=false):
"""proposed at digital sanitation engineering
"""return
sorted(adict.iteritems(), key
=lambda
(k,v): (v,k), reverse
=reverse)
defsbv1(d,reverse
=false):
"""explicit list expansion
"""l
=[(k,v)
for(k,v)
ind.iteritems()]
return
sorted(l, key
=lambda
x: x[
1] , reverse
=reverse)
defsbv2(d,reverse
=false):
"""generator
"""l
=((k,v)
for(k,v)
ind.iteritems())
return
sorted(l, key
=lambda
x: x[
1] , reverse
=reverse)
defsbv3(d,reverse
=false):
"""using a lambda to get the key, rather than 「double-assignment
"""return
sorted(d.iteritems(), key
=lambda
x: x[
1] , reverse
=reverse)
defsbv4(d,reverse
=false):
"""using a formal function to get the sorting key, rather than a lambda
"""def
sk(x):
returnx[1
]
return
sorted(d.iteritems(), key
=sk , reverse
=reverse)
defsk(x):
returnx[1
]def
sbv5(d,reverse
=false):
"""using a formal function, defined in outer scope
to get the sorting key, rather than a lambda
"""return
sorted(d.iteritems(), key
=sk , reverse
=reverse)
from
operator
import
itemgetter
defsbv6(d,reverse
=false):
"""proposed in pep 265, using the itemgetter
"""return
sorted(d.iteritems(), key
=itemgetter(
1), reverse
=true)
d =dict(zip(range(
100),range(
100)))
from
profile
import
runrun(「
forii
inxrange(
10000
): sbv0(d, reverse
=true)」)
run(「
forii
inxrange(
10000
): sbv1(d, reverse
=true)」)
run(「
forii
inxrange(
10000
): sbv2(d, reverse
=true)」)
run(「
forii
inxrange(
10000
): sbv3(d, reverse
=true)」)
run(「
forii
inxrange(
10000
): sbv4(d, reverse
=true)」)
run(「
forii
inxrange(
10000
): sbv5(d, reverse
=true)」)
run(「
forii
inxrange(
10000
): sbv6(d, reverse
=true)」)
具體的結果, 直接拷貝**到你的本機下執行即可知道. 在我這裡, sbv6的時間是0.578s, 最慢的是用generator的sbv2, 22s左右, 其他時間是差不多的, 都是11s左右.
總的來說, pep 265 介紹的方法基本是別的方法十倍左右的速度.
**:
學過的演算法中最快捷 快速排序法
上次總結了其他的三種演算法 選擇排序 氣泡排序和插入排序,這次總結乙個更加高效的排序演算法 快速排序法,如果想要了解其餘三種演算法,請移步c 版選擇法 冒泡法 插入法和快速排序法分析與對比 步驟 現在我們來看看如何實現 為什麼一定要j先找?我們看下邊這種情況,如果i先找,那麼i和j將會在 7 相遇,...
Python 字典的setdefault 方法
setdefault key default if key is in the dictionary,return its value.if not,insert key with a value of default and return default.default defaults to n...
Python 字典的排序
在做 google python exercises 中 basic wordcount.py 這個練習的時候,遇到了乙個關於字典排序的問題。其實很簡單,但是當時做的時候想了好久才找到思路 初學者嘛 於是想把這個問題記錄下來。假設有如下字典 字典的鍵稱作 word,其值稱作 count word c...