0

I am trying to split my list into sublists based on the condition that anything within the element '|' would be considered as the elements for a new sublist. I am ignoring any elements with empty strings so those wont be included in the final list. I have the following list:

slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']

The resulting result would then be:

[['a', 'b', 'c'], ['d', 'e']]

I have written the following code, can someone show me how to solve this please:

start = 0; end = 0
nlist = []
for s in range(0, len(slist)-1):
    ns = s + 1
    if slist[s] == '|' and  ns == '|':
        end = s - 1
    elif slist[s] == '|':
        start = s + 1
        nlist.append(nlist[start:end])
Kaarthik
  • 33
  • 7

4 Answers4

1

One possible solution:

slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']

inList = False
res = []
subl = []
for e in slist:
    if not inList and e == '|':
        # Only to find the start.
        inList = True
    elif inList:
        if e == '|':
            if len(subl) > 0:
                # Append only if subl is not empty
                res.append(subl)
            subl = []
        elif e:
            # Append only non empty elements
            subl.append(e)

res:

[['a', 'b', 'c'], ['d', 'e']]
simre
  • 647
  • 3
  • 9
1

Unless you really need the indices for something, in Python you should rather loop over the elements directly. Then it's just a couple if-s, to decide what to do with the current element:

slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
nlist = [[]]
for x in slist:
  if x != "":               # ignore empty
    if x == "|":
      nlist.append([])      # add a new sub-list
    else:
      nlist[-1].append(x)   # or append the element to the current one

At this point nlist has empty sub-lists:

[[], ['a', 'b', 'c'], [], ['d', 'e'], []]

Which you can filter out with a simple list comprehenstion:

[l for l in nlist if len(l) != 0]

Outputs

[['a', 'b', 'c'], ['d', 'e']]
tevemadar
  • 12,389
  • 3
  • 21
  • 49
1

The split/join technique advocated by @simre works for the data shown in the question. Here's a loop-based approach that may be more flexible:

slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']

result = []
e = []

for v in slist:
    if v == '|':
        if e:
            result.append(e)
            e = []
    elif v:
        e.append(v)

print(result)

Output:

[['a', 'b', 'c'], ['d', 'e']]

This also works where the strings in the list are comprised of more than one character. There is an implicit reliance on the last element in the list being equal to '|'.

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0
slist = ['|', 'a', 'b', 'c', '|', '', '|', 'd', 'e', '|']
relevant =[ i for i , x in enumerate(slist) if x =='|']
i=0
new=[[]]
while(len(slist)>0 and i!=len(relevant)):
    x=slist[relevant[i]+1:relevant[i+1]]
    new[0].append(x)
    i=i+2
print(new)

Another way

DontDownvote
  • 182
  • 7