📜  Python - 按最大 ASCII 值对字符串进行排序

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

Python - 按最大 ASCII 值对字符串进行排序

给定字符串列表,按字符串中的最大字符进行排序。

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

在这种情况下,使用sort()进行排序, max()用于从字符串中获取最大字符。

Python3
# Python3 code to demonstrate working of
# Sort Strings by Maximum Character
# Using sort() + max()
  
# get maximum character fnc.
def get_max(sub):
  
    # returns maximum character
    return ord(max(sub))
  
  
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "cs"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# performing sorting
test_list.sort(key=get_max)
  
# printing result
print("Sorted List : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort Strings by Maximum Character
# Using sorted() + lambda + max()
  
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "cs"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# performing sorting using sorted()
# lambda function provides logic
res = sorted(test_list, key=lambda sub: ord(max(sub)))
  
# printing result
print("Sorted List : " + str(res))


输出:

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

在这里,我们使用sorted()执行排序任务, lambdamax()用于输入获取最大字符的逻辑。

蟒蛇3

# Python3 code to demonstrate working of
# Sort Strings by Maximum Character
# Using sorted() + lambda + max()
  
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "cs"]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# performing sorting using sorted()
# lambda function provides logic
res = sorted(test_list, key=lambda sub: ord(max(sub)))
  
# printing result
print("Sorted List : " + str(res))

输出: