📜  Python - 按字符串列表中的后字符排序

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

Python - 按字符串列表中的后字符排序

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

方法#1:使用sort()

在这里,我们使用 sort() 执行排序任务,外部函数用于获取字符串中的后部元素的任务。

Python3
# Python3 code to demonstrate working of
# Sort by Rear Character in Strings List
# Using sort()
 
# sort key function
def get_rear(sub):
    return sub[-1]
 
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list is : " + str(test_list))
 
# using sort with key fnc.
# performs inplace sort
test_list.sort(key = get_rear)
 
# printing result
print("Sorted List : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort by Rear Character in Strings List
# Using sorted() + lambda
 
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list is : " + str(test_list))
 
# lambda function for rear element
# performs non-inplace sort
res = sorted(test_list, key = lambda sub : sub[-1])
 
# printing result
print("Sorted List : " + str(res))


输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'is', 'geeks', 'best']

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

在此,我们使用 sorted() 执行排序,显式,并使用 lambda函数执行获取后部元素的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Sort by Rear Character in Strings List
# Using sorted() + lambda
 
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list is : " + str(test_list))
 
# lambda function for rear element
# performs non-inplace sort
res = sorted(test_list, key = lambda sub : sub[-1])
 
# printing result
print("Sorted List : " + str(res))
输出
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'is', 'geeks', 'best']