📜  Python - 按元素中的最大数字排序

📅  最后修改于: 2022-05-13 01:55:09.504000             🧑  作者: Mango

Python - 按元素中的最大数字排序

给定一个元素列表,按列表中元素的最大数字排序。

方法 #1:使用max() + sort()

在这里,我们使用 sort() 执行就地排序任务,并使用 max() 提取最大元素。

Python3
# Python3 code to demonstrate working of 
# Sort by Maximum digit in Element
# Using max() + sort()
  
def max_dig(ele):
      
    # getting maximum digit by magnitude
    return max(str(ele))
  
# initializing list
test_list = [234, 92, 15, 8, 721]
  
# printing original list
print("The original list is : " + str(test_list))
  
# calling sort fnc. to sort with key
test_list.sort(key = max_dig)
  
# printing result 
print("Sorted List : " + str(test_list))


Python3
# Python3 code to demonstrate working of 
# Sort by Maximum digit in Element
# Using sorted() + lambda + max()
  
# initializing list
test_list = [234, 92, 15, 8, 721]
  
# printing original list
print("The original list is : " + str(test_list))
  
# lambda fnc. used to get maximum Element logic
res = sorted(test_list, key = lambda ele : max(str(ele)))
  
# printing result 
print("Sorted List " + str(res))


输出
The original list is : [234, 92, 15, 8, 721]
Sorted List : [234, 15, 721, 8, 92]

方法 #2:使用sorted() + lambda + max()

在这里,我们使用 sorted() 执行非就地排序,并避免使用 lambda函数使用外部函数来获取最大数字。

蟒蛇3

# Python3 code to demonstrate working of 
# Sort by Maximum digit in Element
# Using sorted() + lambda + max()
  
# initializing list
test_list = [234, 92, 15, 8, 721]
  
# printing original list
print("The original list is : " + str(test_list))
  
# lambda fnc. used to get maximum Element logic
res = sorted(test_list, key = lambda ele : max(str(ele)))
  
# printing result 
print("Sorted List " + str(res))
输出
The original list is : [234, 92, 15, 8, 721]
Sorted List [234, 15, 721, 8, 92]