เมื่อจำเป็นต้องแยกสตริงตามการเกิดขึ้นของคำนำหน้า จะมีการกำหนดรายการว่างสองรายการ และกำหนดค่าส่วนนำหน้า ใช้การวนซ้ำอย่างง่ายร่วมกับวิธี "ผนวก"
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
from itertools import zip_longest
my_list = ["hi", 'hello', 'there',"python", "object", "oriented", "object", "cool", "language", 'py','extension', 'bjarne']
print("The list is : " )
print(my_list)
my_prefix = "python"
print("The prefix is :")
print(my_prefix)
my_result, my_temp_val = [], []
for x, y in zip_longest(my_list, my_list[1:]):
my_temp_val.append(x)
if y and y.startswith(my_prefix):
my_result.append(my_temp_val)
my_temp_val = []
my_result.append(my_temp_val)
print("The resultant is : " )
print(my_result)
print("The list after sorting is : ")
my_result.sort()
print(my_result) ผลลัพธ์
The list is : ['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne'] The prefix is : python The resultant is : [['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']] The list after sorting is : [['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']]
คำอธิบาย
-
แพ็คเกจที่จำเป็นจะถูกนำเข้าสู่สภาพแวดล้อม
-
รายการสตริงถูกกำหนดและแสดงบนคอนโซล
-
ค่านำหน้าถูกกำหนดและแสดงบนคอนโซล
-
มีการกำหนดรายการว่างสองรายการ
-
วิธี 'zip_longest' ใช้เพื่อรวมรายการเข้ากับรายการเดียวกันโดยละเว้นค่าแรกในการวนซ้ำ
-
องค์ประกอบจะถูกผนวกเข้ากับหนึ่งในรายการที่ว่างเปล่า
-
รายการนี้จะแสดงเป็นเอาต์พุตบนคอนโซล
-
รายการนี้จะถูกจัดเรียงและแสดงบนคอนโซลอีกครั้ง