Python程序按子字符串范围对字符串进行排序
给定一个字符串列表,按子字符串的范围排序。
Input : test_list = [“geeksforgeeks”, “best”, “geeks”, “preparation”, “interview”], i, j = 1, 3
Output : [‘geeksforgeeks’, ‘geeks’, ‘best’, ‘interview’, ‘preparation’]
Explanation : “eek” < “eek” < “est” < “nte” < “rep”.
Input : test_list = [“apple”, “orange”, “banana”], i, j = 2, 4
Output : [‘orange’, ‘banana’, ‘apple’]
Explanation : “ang” < “nan” < “ple”.
方法 #1:使用 sort() + 切片
在这里,我们使用 sort() 执行排序任务,使用切片完成提取范围的任务。
Python3
# Python3 code to demonstrate working of
# Sort Strings By Substring Range
# Using sort() + slicing
# helper function
def get_substr(test_str):
# getting range
return test_str[i : j]
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 1, 3
# calling func.
test_list.sort(key=get_substr)
# printing result
print("Strings after sorting : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Strings By Substring Range
# Using lambda function + sort() + slicing
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 1, 3
# lambda function providing sort fnc.
test_list.sort(key=lambda test_str : test_str[i : j])
# printing result
print("Strings after sorting : " + str(test_list))
The original list is : [‘geeksforgeeks’, ‘best’, ‘geeks’, ‘preparation’]
Strings after sorting : [‘geeksforgeeks’, ‘geeks’, ‘best’, ‘preparation’]
方法 #2:使用 lambda函数+ sort() + 切片
在这种情况下,我们使用 lambda函数而不是调用外部函数来执行切片。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Strings By Substring Range
# Using lambda function + sort() + slicing
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "preparation"]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 1, 3
# lambda function providing sort fnc.
test_list.sort(key=lambda test_str : test_str[i : j])
# printing result
print("Strings after sorting : " + str(test_list))
The original list is : [‘geeksforgeeks’, ‘best’, ‘geeks’, ‘preparation’]
Strings after sorting : [‘geeksforgeeks’, ‘geeks’, ‘best’, ‘preparation’]