I have a list in which each item is a sentence. I want to join the items as long as the new combined item does not go over a character limit.
You can join items in a list fairly easily.
x = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
' '.join(x)
>>> 'Alice went to the market. She bought an apple. And she then went to the park.'
Now say I would like to sequentially join the items as long as the new combined item is not greater than 50 characters.
The result would be :
['Alice went to the market. She bought an apple.','And she then went to the park.']
You can maybe do a list comprehension like here. Or I can maybe do a conditional iterator like here. But I run into problems where the sentences get cut off.
Clarifications
- The max character limit refers to the length of a single item in the list...not the length of the entire list. When the list items are combined, no single item in the new list can be over the limit.
- The items that were not able to be combined are returned in the list as they were unchanged.
- Combine sentences together as long as they do not exceed limit. If they exceed limit, do not combine and keep as is. Only combine sentences that are sequentially next to each other in the list.
- Please make sure your solution satisfies the output result as indicated previously above :
['Alice went to the market. She bought an apple.','And she then went to the park.']