Comparing and merging 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 the previous element. And if they are not me, I just join the first element. For example, 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

+4
source share
3 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))

Conclusion:

('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.')
+3
source

Hope this does what you are looking for. I did this 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)
+3
source

, . , , .

phrases = ['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.']
def join_on_uppercase(items):
  final_phrases = []
  temp_list = [phrases[0]]
  for phrase in phrases[1:]:
    if phrase[0].isupper():
      final_phrases.append(' '.join(temp_list))
      temp_list = []
    temp_list.append(phrase)
  final_phrases.append(' '.join(temp_list))
  return tuple(final_phrases)
print(join_on_uppercase(phrases))

. temp_list.

+3

Source: https://habr.com/ru/post/1694011/


All Articles