- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Group contiguous strings in List
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’.
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)
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]
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.
- Group Shifted Strings in C++
- Python - Contiguous Boolean Range
- Python Group Anagrams from given list
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Python Program to Group Strings by K length Using Suffix
- Extract numbers from list of strings in Python
- Python - Custom space size padding in Strings List
- Largest product of contiguous digits in Python
- How to remove empty strings from a list of strings in Python?
- Python - Ways to merge strings into list
- Python Group tuples in list with same first value
- Bootstrap Collapsible list group
- Bootstrap list-group class
- Converting all strings in list to integers in Python