📜  Python – 基于反向字符串排序

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

Python – 基于反向字符串排序

给定一个字符串列表,根据字符串的反转对列表进行排序。

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

这是可以执行此任务的方式之一。在此,我们首先反转每个元素,执行排序,然后再次反转每个字符串以获得结果排序。

Python3
# Python3 code to demonstrate working of 
# Sort on basis of reverse Strings
# Using reverse() + sort()
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original list
print("The original list : " + str(test_list))
  
# reverse() to reverse each string 
res = []
for ele in test_list:
    res.append("".join(reversed(ele))) 
      
# sorting to get required ordering 
res.sort()
  
# reverse each element again
test_list = []
for ele in res:
    test_list.append("".join(reversed(ele))) 
      
# printing result 
print("List after sorting on reversed strings : " + str(test_list))


Python3
# Python3 code to demonstrate working of 
# Sort on basis of reverse Strings
# Using list slicing + sort()
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original list
print("The original list : " + str(test_list))
  
# [::-1] to reverse each string 
# sort() to sort
test_list.sort(key = lambda sub: sub[::-1])
  
# printing result 
print("List after sorting on reversed strings : " + str(test_list))


输出
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
List after sorting on reversed strings : ['gfg', 'for', 'is', 'geeks', 'best']

方法 #2:使用列表切片 + sort()

这是可以执行此任务的另一种方式。在此列表中,切片用于执行反向操作,而 sort() 用于排序,在一个衬里。

Python3

# Python3 code to demonstrate working of 
# Sort on basis of reverse Strings
# Using list slicing + sort()
  
# initializing list
test_list = ["gfg", "is", "best", "for", "geeks"]
  
# printing original list
print("The original list : " + str(test_list))
  
# [::-1] to reverse each string 
# sort() to sort
test_list.sort(key = lambda sub: sub[::-1])
  
# printing result 
print("List after sorting on reversed strings : " + str(test_list))
输出
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
List after sorting on reversed strings : ['gfg', 'for', 'is', 'geeks', 'best']