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
让我们看看解决问题的另一种方法。我们将对函数进行排序以解决问题。请按照以下步骤编写代码。
将列表传递给已排序的函数。
编写一个名为get_key的函数,该函数接受两个参数。
如果str(first)+str(second)>str(second)+str(first)则返回-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
结论
如果您对本教程有任何疑问,请在评论部分中提及。