user271528
user271528

Reputation:

Trim list to delimiter

Say you have the list

`[1, 0, -1, 0, ';', 2, 0, 0, -1, ';', 0, 1, 0, -1, ';', 0, 1, -2, 0, ';', 0, 3, -6, 0, ';']`

What is the easiest way to trim this backwards to say the second occurrence of ';', outputting

[1, 0, -1, 0, ';', 2, 0, 0, -1, ';', 0, 1, 0, -1, ';', 0, 1, -2, 0]

Upvotes: 0

Views: 212

Answers (2)

Pierre GM
Pierre GM

Reputation: 20339

If you have a list as input, you can try to find the indices of the ";" and work from there:

>>> L = [1, 0, -1, 0, ';', 2, 0, 0, -1, ';', 0, 1, 0, -1, ';', 0, 1, -2, 0, ';', 0, 3, -6, 0, ';']
>>> idx = [i for (i,v) in enumerate(L) if v == ";"]
>>> L[:idx[-2]]
[1, 0, -1, 0, ';', 2, 0, 0, -1, ';', 0, 1, 0, -1, ';', 0, 1, -2, 0, ';', 0, 3, -6, 0, ';']

Upvotes: 5

mgilson
mgilson

Reputation: 310089

def get_part(lst,sep=';'):
    out = []
    for i in lst:
        if i == sep:
           yield out
           out = []
        else:
           out.append(i)

(which you already have from your previous question).

Now, to trim it, we need to convert to a list:

lst = list(get_part(yourlist))
output_list = []
for part in lst[:-2]:
   output_list.extend(part)
   output_list.append(';')

But my previous advice still holds. A better data structure is a list of lists.

Upvotes: 1

Related Questions