In python, how to cut a list by specific item?

  • A+
Category:Languages

I'm trying to cut a list by specific items in it, for example, I have a list like this:

down = ["a", "b", "c", "d", "b", "e", "r"] 

What I want is

[["a", "b"]["c", "d", "b"] ["e", "r"]] 

which is cut after every occurrence of "b".

I wrote something like this:

down = ["a", "b", "c", "d", "b", "e", "r"] up = [] while down is not []:     up, down = up.append(down[:(down.index("b") + 1)]), down[(down.index("b") + 1):] 

It throws an error:

AttributeError: 'NoneType' object has no attribute 'append' 

I can't figure out what's wrong.

 


You can iterate your original and assemble the sublists in a second list:

k = ["a", "b", "c", "d", "b", "e", "r"]  result = [[]] for e in k:     if e != "b":         result[-1].append(e)     else:         result[-1].append(e)         result.append([])  if result[-1] == []:      result.pop() # thx iBug's comment  print(result) # [['a', 'b'], ['c', 'd', 'b'], ['e', 'r']] 

I think that is much clearer then what your code tries to do - your "what I want ["a", "b"]["c", "d", "b"] ["e", "r"]" is not valid python.


A slightly less performant code would be:

k = ["a", "b", "c", "d", "b", "e", "r"] b = [] while True:     try:         b_idx = k.index("b")     except:          b.append(k)         break     else:         b,k = b+[k[:b_idx+1]],k[b_idx+1:] print(b)  

But you need far mor searches into your list via .index() and try: except so it has a worse performace then simply iterating the list once.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: