用子串範圍對字串進行排序的 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”的方法,它將一個字串作為引數。
它使用列表切片來獲取給定範圍內的值。
在方法外部,定義一個字串列表並將其顯示在控制檯上。
定義兩個變數的值並將其顯示在控制檯上。
該列表將根據作為先前定義的方法的鍵進行排序。
該列表將作為輸出顯示在控制檯上。
廣告