Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove elements from list of strings while traversing [duplicate]

how to remove elements from a list of strings while traversing through it. I have a list

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

i want to remove $ fro the list and if a ) or )% or % comes add that to the previous elemt of the list.
expected output is :

['', '32,324', '32', '(35)', '32,321']

what i have tried is

for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      list1[j-1] = list1[j-1] + element
      list1.pop(j)
   elif element == '$':
      list1.pop(j)

but the output i am getting is

['', '32,324', '32', '(35)', '$', '32,321']

whis is not the expected output. Please help

This question is different from the suggested reference is, here I have to do a concatenation with the previous element if the current element is ),)% or %.

like image 467
Shijith Avatar asked Mar 04 '23 22:03

Shijith


2 Answers

What Green Cloak Guy said is mostly correct. Editing the size of the list (by calling .pop()) is causing you to have an unexpected j value. To me, the easiest way to fix this problem while keeping your existing code is to simply not mutate your list, and build up a new one instead:

new_list = []
for j,element in enumerate(list1):
   if element == '%' or element == ")%" or element ==')':
      ret[len(ret) - 1] += element  # add at the end of the previous element
   elif element != '$':
      new_list.push(element)

However, I would encourage you to think about your edge cases here. What happens when a ')' is followed by another ')' in your list? This may be a special case in your if statement. Hope this helped!

like image 110
Ryan Drew Avatar answered Apr 28 '23 03:04

Ryan Drew


Instead of attempting to remove and merge elements dynamically while iterating on the list, it will be much easier to make a new list based on the conditions here.

list1 = ['', '$', '32,324', '$', '32', '$', '(35', ')', '$', '32,321']

out = []
for element in list1:
    if element == "$":
        continue #skip if $ present
    elif element in ("%", ")", ")%"):
        out[-1] = out[-1] + element #merge with last element of out so far.
    else:
        out.append(element)

print(out)
#Output:
['', '32,324', '32', '(35)', '32,321']
like image 20
Paritosh Singh Avatar answered Apr 28 '23 03:04

Paritosh Singh