Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing and Concatenating Tuples in Python

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

like image 535
TheSoldier Avatar asked Jan 02 '23 18:01

TheSoldier


2 Answers

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.')
like image 153
Ajax1234 Avatar answered Jan 14 '23 11:01

Ajax1234


Hope this does what you are looking for. I did it without using any external modules.

b = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.')
i=0
a=[]
num=0
for element in b:
    print(element)
    if element[i][0].islower():
        a[-1]=a[-1]+element
    else:
        a.append(element)
        num=num+1
print(a)
like image 38
Abhisek Roy Avatar answered Jan 14 '23 10:01

Abhisek Roy