Extract elements when a condition is met in different lines and storing them in one

Viewed 71

I have elements in a list as:

temp_list = ["% Work\n"," Hard\n"," Or\n"," Go\n"," Home\n","%","% Happy Coding","%"]

I want to achieve this:

final_list = ["Work Hard Or Go Home","Happy Coding"]

The percentage sign in the elements is the separator between two comments of new lines.

3 Answers

Join the words and then split on %:

temp_list = ["% Work\n"," Hard\n"," Or\n"," Go\n"," Home\n","%","% Happy Coding","%"]

final_list = []
for line in map(str.strip, "".join(temp_list).split("%")):
    if not line:
        continue
    final_list.append(line.replace("\n", ""))

print(final_list)

Prints:

['Work Hard Or Go Home', 'Happy Coding']

You can accomplish this using the iterators map, filter, and some string functions lstrip and replace

map takes a function and an iterator applies the function to every element and returns a new iterator

filter takes a function and an iterable, removes elements who do not return true when its function is called on them.

lstrip remove whitespace from left side of string

replace(a,b) replaces a with b in string

flat = ""
# Make a normal string from your array
for elem in temp_list:
    flat += elem

# First separate string by %
# Next filter out empty list elements
# Replace every \n with nothing and remove whitespace from left side.
your_groupings = list(
      map(lambda el: el.replace("\n","").lstrip(),  
      filter(lambda el: len(el) != 0,  
         flat.split("%")))) 
print(your_groupings)
> ['Work Hard Or Go Home', 'Happy Coding']
ls=[]
msg=""
for i in temp_list:
    if i=="%":
        ls.append (msg [1:].strip ().replace ("\n",""))
        msg=""
    else:
        msg+=i
print(ls)

Here.. check for "%" if element is "%" then u need add msg to the list by removing spaces and replacing "\n" with "". Else append i to msg

Related