When it is required to group the contiguous elements of a string that are present in a list, a method is defined that uses ‘groupby’, and ‘yield’.
Example
Below is a demonstration of the same
from itertools import groupby def string_check(elem): return isinstance(elem, str) def group_string(my_list): for key, grp in groupby(my_list, key=string_check): if key: yield list(grp) else: yield from grp my_list = [52, 11, 'py', 'th', 'on', 11, 52, 'i', 's', 18, 'f', 'un', 99] print("The list is :") print(my_list) my_result = [*group_string(my_list)] print("The result is:") print(my_result)
Output
The list is : [52, 11, 'py', 'th', 'on', 11, 52, 'i', 's', 18, 'f', 'un', 99] The result is: [52, 11, ['py', 'th', 'on'], 11, 52, ['i', 's'], 18, ['f', 'un'], 99]
Explanation
A method named ‘string_check’ is defined that takes a list as parameter and checks to see if it belongs to a certain instance type.
Another method named ‘group_string’ is defined that takes a list as parameter and uses yield to return the output using ‘groupby’ method.
Outside the method, a list is defined and is displayed on the console.
The ‘group_string’ is called and the result is assigned to a variable.
This is displayed as output on the console.