溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python實現(xiàn)自定義sorted排序的方法

發(fā)布時間:2020-11-03 16:36:31 來源:億速云 閱讀:250 作者:Leah 欄目:開發(fā)技術

Python實現(xiàn)自定義sorted排序的方法?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

def compare(strNum1, strNum2):
  newStrNum1 = strNum1 + strNum2
  newStrNum2 = strNum2 + strNum1
  if newStrNum2 > newStrNum1:
    return -1
  elif newStrNum2 == newStrNum1:
    return 0
  else:
    return 1

問題

排序規(guī)則定義好了,但是問題來了,一般的 sorted 排序函數(shù) 都有相應的 cmp函數(shù),用來定制化排序的比較方法。但是python3的sorted函數(shù)已經(jīng)刪去了cmp參數(shù),真不能跑去用python2吧

解決方案

由于python3中sorted函數(shù)除去compare函數(shù),無法自定義排序規(guī)則,所以使用內(nèi)置的函數(shù),將cmp函數(shù)轉(zhuǎn)化為key的值

Note:

functools.cmp_to_key() 將 cmp函數(shù) 轉(zhuǎn)化為 key。

cmp函數(shù)的返回值 必須為 [1,-1,0]

python

from functools import cmp_to_key

def compare(strNum1, strNum2):
	"""
	返回最小排列的定義,如果需要最大,將返回值的+1、-1調(diào)換即可
	"""
  newStrNum1 = strNum1 + strNum2
  newStrNum2 = strNum2 + strNum1
  if newStrNum2 > newStrNum1:
    return -1
  elif newStrNum2 == newStrNum1:
    return 0
  else:
    return 1

def print_min_nums(nums):
  if not nums:
    return 0

  arr = [str(i) for i in nums]
  newarr = sorted(arr,key=cmp_to_key(compare))
  return "".join(newarr)


if __name__ == '__main__':
  print(print_min_nums([3,32,321]))

看完上述內(nèi)容,你們掌握Python實現(xiàn)自定義sorted排序的方法的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI