Python - 從給定數字列表中獲取最大可能的數字


在本文中,我們將學習如何從給定的數字列表中找到最大的可能數字。我們將看到兩種不同的方法來解決這個問題。請按照以下步驟解決問題。

  • 匯入itertools模組用於排列方法。
  • 用數字和空列表初始化列表。
  • 迭代列表的排列。
    • 連線所有組合並將結果新增到空列表。
  • 使用max方法和int作為鍵從結果中查詢最大數。
  • 將字串轉換為整數並列印。

示例

讓我們看看程式碼。

 線上演示

# importing the module
import itertools

# initializing the list
numbers = [45, 35, 138, 43, 67]

# result
result = []

# permutations
for permutation in itertools.permutations(str(number) for number in numbers):
   result.append(''.join(permutation))

# finding max
maximum = max(result, key=int)

# printing the max
print(int(maximum))

如果執行上述程式碼,則會得到以下結果。

輸出

67454335138

讓我們看看另一種解決問題的方法。我們將使用sorted函式來解決這個問題。請按照以下步驟編寫程式碼。

  • 將列表傳遞給sorted函式。
  • 編寫一個名為get_key的函式,該函式接受兩個引數。
  • 如果str(first) + str(second) > str(second) + str(first),則返回-1,否則返回1。
  • 使用join方法連線列表元素。
  • 透過轉換為整數來列印結果。

由於我們使用函式作為鍵,因此必須使用functools中的cmp_to_key方法將其轉換為鍵。讓我們看看程式碼。

示例

 線上演示

from functools import cmp_to_key

# initializing the list
numbers = [45, 35, 138, 43, 67]

def get_key(first, second):
   if str(first) + str(second) > str(second) + str(first):
      return -1
   return 1

# getting the result
result = sorted(numbers, key=cmp_to_key(get_key))

# joining the result
result = "".join(str(integer) for integer in result)

# printing the result
print(int(result))

如果執行上述程式碼,則會得到以下結果。

輸出

67454335138

結論

如果您在本教程中遇到任何疑問,請在評論區提出。

更新於:2020年11月13日

1K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告