![](/img/trans.png)
[英]How to fix 'TypeError: __init__() got an unexpected keyword argument 'sender''
[英]How to fix 'TypeError: invalid keyword argument for sort()'
使用compare_points
函數訂購二維點的列表。
我不明白如何將compare_points
函數傳遞給sort()
方法。
def compare_points( p, q ):
if p[0] < q[0] or (p[0] == q[0] and p[1] < q[1]):
return -1
elif p[0] > q[0] or (p[0] == q[0] and p[1] > q[1]):
return 1
else:
return 0
#print(compare_points( [1,3], [5,6])) # outputs -1
#print(compare_points( [1,3], [1,6])) # ouputs -1
#print(compare_points( [1,3], [1,3])) # outputs 0
#print(compare_points( [1,3], [0,3])) # outputs 1
L = [ [5,8], [5,2], [12, 3], [1,3], [10,2], [12,1], [12,3] ]
L.sort(cmp=compare_points)
print(L)
實際結果:
L.sort(cmp=compare_points)
builtins.TypeError: 'cmp' is an invalid keyword argument for sort()
預期成績:
L = [ [1,3], [5,2], [5,8], [10,2], [12,1], [12,3], [12,3] ]
實際上,這里根本不需要指定鍵,因為您在此處定義的基本上只是字典順序 ,這是在Python中對列表進行排序的標准方式。
因此,您可以在不指定鍵的情況下進行排序,例如:
>>> L = [ [5,8], [5,2], [12, 3], [1,3], [10,2], [12,1], [12,3] ]
>>> L.sort()
>>> L
[[1, 3], [5, 2], [5, 8], [10, 2], [12, 1], [12, 3], [12, 3]]
在python-2.x中 , .sort(..)
函數確實可以采用cmp=...
參數,該參數是兩個值之間的比較器。 從python-3.x開始 ,這個參數已經被刪除 。
使用鍵排序更有效,因為它避免了實現無效的比較函數:比較函數應該是反身 , 反對稱和可傳遞的 。 一些比較功能不滿足這些條件。
您正在python3中使用Python3,關鍵字參數為key,因此您應該這樣做
L.sort(key=compare_points)
如果要使用cmp關鍵字參數完成此操作,則應使用Python2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.