जब प्रीफिक्स की घटना के आधार पर स्ट्रिंग्स को विभाजित करना आवश्यक हो, तो दो खाली सूचियां परिभाषित की जाती हैं, और एक प्रीफिक्स मान परिभाषित किया जाता है। 'append' विधि के साथ एक साधारण पुनरावृत्ति का उपयोग किया जाता है।
उदाहरण
नीचे इसका प्रदर्शन दिया गया है:
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' विधि का उपयोग पहली वैल्यू को छोड़कर समान सूची के साथ सूची को संयोजित करने के लिए एक पुनरावृत्ति में किया जाता है।
तत्वों को खाली सूची में से एक में जोड़ा जाता है।
इस सूची को कंसोल पर आउटपुट के रूप में प्रदर्शित किया जाता है।
इस सूची को फिर से क्रमबद्ध किया जाता है और कंसोल पर प्रदर्शित किया जाता है।