Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Selective consecutive Suffix Join
When working with lists of strings, you may need to group consecutive elements that end with a specific suffix. This technique uses simple iteration with the endswith() method to join elements until a non-suffix element is found.
Example
Below is a demonstration of selective consecutive suffix join ?
my_list = ["Python-", "fun", "to-", "code"]
print("The list is :")
print(my_list)
suffix = '-'
print("The suffix is :")
print(suffix)
result = []
temp = []
for element in my_list:
temp.append(element)
if not element.endswith(suffix):
result.append(''.join(temp))
temp = []
print("The result is :")
print(result)
The output of the above code is ?
The list is : ['Python-', 'fun', 'to-', 'code'] The suffix is : - The result is : ['Python-fun', 'to-code']
How It Works
The algorithm groups consecutive elements by:
- Creating an empty
resultlist to store final grouped strings - Using a temporary
templist to accumulate elements - Adding each element to
tempas we iterate - When an element doesn't end with the suffix, joining all accumulated elements and adding to
result - Resetting
tempto start a new group
Alternative Implementation
Here's a more compact version using list comprehension and grouping logic ?
def consecutive_suffix_join(data, suffix):
result = []
temp = []
for item in data:
temp.append(item)
if not item.endswith(suffix):
result.append(''.join(temp))
temp = []
# Handle any remaining items
if temp:
result.append(''.join(temp))
return result
words = ["hello-", "world", "test-", "data", "end-", "final"]
grouped = consecutive_suffix_join(words, '-')
print(grouped)
['hello-world', 'test-data', 'end-final']
Conclusion
Selective consecutive suffix join groups elements by accumulating them until a non-suffix element is found. This technique is useful for processing structured text data where certain delimiters indicate continuation.
Advertisements
