How can I merge items in a list based on a rule that involves multiple list items in python?

Question:

Problem: I want to join items of a list whenever such items are separated by three empty list items.

Example input:

input_list = ["hi.", "", "", "", "join me", "", "", "", "hey", "", "", "", "join me too"]

Output:

output_list = ["hi.join me", "heyjoinmetoo"]

I’m not sure where to start but here is some pseudocode that I thought might work?

  1. Iterate through the list and check if the list item is empty or not
  2. If it is empty, somehow keep track of how many empty list items have been iterated over.
  3. When that number is 3, merge the list item 3 places ago and the next item together.
  4. Keep going until there are never 3 empty items.

Does this logic make sense? And if so, how would I begin writing this loop?

Asked By: ars

||

Answers:

You can use this:

list = ["hi.", "", "", "", "join me", "", "", "", "hey", "", "", "", "join me too"]

ind =0
new_list = []

while(ind+4<len(list)):
    if list[ind]!="" and list[ind+1:ind+4]==["","",""]:
        new_list.append(list[ind]+list[ind+4])
        ind+=4
    ind+=1
print(new_list)

Output:

['hi.join me', 'heyjoin me too']
Answered By: Kedar U Shet

Just use string.join(list). Here is the code:

input_list = ["hi.", "", "", "", "join me", "", "", "", "hey", "", "", "", "join me too"]
output_list = []
ls = []
for i in input_list:
    print(ls)
    ls.append(i)
    if i == "join me" or i == "join me too":
        output_list.append("".join(ls))
        ls.clear()
print(output_list)
    

If this answers your question you can tick this answer

Answered By: ss3387
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.