pythoncmp
㈠ python3 為什麼取消了sort方法中的cmp參數
使用functools.cmp_to_key 即可。
附通過的代碼:
class Solution:
# @param {integer[]} nums
# @return {string}
def largestNumber(self, nums):
from functools import cmp_to_key
key = cmp_to_key(lambda x,y: int(y+x)-int(x+y))
res = ''.join(sorted(map(str, nums), key=key)).lstrip('0')
return res or '0'
㈡ python編程中cmp()函數是什麼意思
cmp( x, y)
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.
比較2個對象,前者小於後者返回-1,相等則返回0,大於後者返回1.
㈢ python cmp import什麼模塊
cmp是Python自帶的比較函數,無需import模塊。
參照官方手冊:
https://docs.python.org/2/library/functions.html#cmp
㈣ python cmp & sorted
你理解錯了
sorted函數的cmp參數,表示對序列排序的具體實現。你的mycmp就是實現,他是將mylist中的元素的第二個子元素進行兩兩比較,並按照從小到大的順序排列。這樣就得到了結果[['c', 0], ['a', 1], ['b', 4]]
㈤ 關於python3沒有cmp,如何代替的問題
>>>sorted(['bob','Bob','about','Zoo','Credit'],key=str.lower)
['about','bob','Bob','Credit','Zoo']
忽略大小寫的比較,先轉小寫作為鍵值排序
㈥ python中比較大小的偏函數中,為什麼還要寫一個'cmp=',
3開始沒這個函數了,官方文檔是這么寫的
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
大意就是cmp()函數已經「離開」了,如果你真的需要cmp()函數,你可以用表達式(a > b) - (a < b)代替cmp(a,b)