Python - 按最大 ASCII 值对字符串进行排序
给定字符串列表,按字符串中的最大字符进行排序。
Input : test_list = [“geeksforgeeks”, “is”, “best”, “cs”]
Output : [“geeksforgeeks”, “is”, “cs”, “best”]
Explanation : s = s = s < t, sorted by maximum character.
Input : test_list = [“apple”, “is”, “fruit”]
Output : [“apple”, “is”, “fruit”]
Explanation : p < s < t, hence order retained after sorting by max. character.
方法 #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))
输出:
The original list is : [‘geeksforgeeks’, ‘is’, ‘best’, ‘for’, ‘cs’]
Sorted List : [‘for’, ‘geeksforgeeks’, ‘is’, ‘cs’, ‘best’]
方法 #2:使用 sorted() + lambda + max()
在这里,我们使用sorted()执行排序任务, lambda和max()用于输入获取最大字符的逻辑。
蟒蛇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))
输出:
The original list is : [‘geeksforgeeks’, ‘is’, ‘best’, ‘for’, ‘cs’]
Sorted List : [‘for’, ‘geeksforgeeks’, ‘is’, ‘cs’, ‘best’]