เมื่อต้องการเรียงลำดับสตริงตามช่วง substring ที่กำหนด สามารถกำหนดฟังก์ชันช่วยที่ใช้ list slicing ได้
ตัวอย่าง
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คืนค่า substring ตำแหน่ง i ถึง j-1 ของสตริงที่รับเข้ามา (ใช้ตัวแปร global i, j)กำหนดลิสต์สตริง ค่า i, j แสดงผล
ใช้
sort()เรียงลำดับลิสต์โดยระบุkey=get_substringแสดงผลลัพธ์ที่เรียงตาม substring ตำแหน่งที่ 1-2 (เช่น 'yt', 's', 'un', 'o', 'ea')