用子串范围对字符串进行排序的 Python 程序
当需要根据子串范围对字符串进行排序时,该方法利用列表切片来确定结果。
示例
以下是示范 −
def get_substring(my_string):
return my_string[i : j]
my_list = ["python", 'is', 'fun', 'to', 'learn']
print("The list is :")
print(my_list)
i, j = 1, 3
print("The value of i and j are :")
print(str(i)+ ',' +str(j))
my_list.sort(key=get_substring)
print("The result is :")
print(my_list)输出
The list is : ['python', 'is', 'fun', 'to', 'learn'] The value of i and j are : 1,3 The result is : ['learn', 'to', 'is', 'fun', 'python']
说明
定义一个名为“get_substring”的方法,它将一个字符串作为参数。
它使用列表切片来获取给定范围内的值。
在方法外部,定义一个字符串列表并将其显示在控制台上。
定义两个变量的值并将其显示在控制台上。
该列表将根据作为先前定义的方法的键进行排序。
该列表将作为输出显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP