Comparing and Concatenating Tuples in Python Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Comparing and Concatenating Tuples in Python without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a python tuple whose elements are actually sentences. I want to compare the first letters of each element and if they are lowercase, I join it to the previous element. And if they aren’t I just join the first element. For instance if I have:

tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.')

My result should be:

tuple1 = ('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.')

This is my working code:

i=0 
while i<(len(tuple1)-1):
   if tuple1[i+1][0].islower():
       tuple1[i] + " " + tuple[i+1]
   i+=1

How can I achieve this? Thanks

Answer

You can use itertools.groupby:

import itertools  
tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.')
new_data = tuple(' '.join(i[-1] for i in b) for _, b in itertools.groupby(enumerate(tuple1), key=lambda x:x[-1][0].islower() or tuple1[x[0]+1][0].islower() if x[0]+1 < len(tuple1) else True))

Output:

('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.')
We are here to answer your question about Comparing and Concatenating Tuples in Python - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji