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 get the error because you assign the result of the list.append()
function - which is None
- to up
in
up, down = up.append(down[: (down.index("b") + 1)]), down[...snipp...] # ^^^^^^^^ returns None
list.append
is a "in-place" operation that returns None
so up
is going to be None
in the next iteration.
Keeping closest to what you got you could use
down = ["a", "b", "c", "d", "b", "e", "r"]
up = []
while 'b' in down:
b_index = down.index('b') + 1
up.append(down[:b_index])
down = down[b_index:]
up.append(down)
but simply iterating your original and assembling the sublists in a second list is cleaner in my opinion:
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 different version of the 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 performance then simply iterating the list once.
down = ["a", "b", "c", "d", "b", "e", "r"]
poslist = []
for pos, item in enumerate(down):
if item == 'b':
poslist.append(pos)
answerlist = []
for i in range(len(poslist)):
if i == 0:
answerlist.append(down[:poslist[i]+1])
else:
answerlist.append(down[poslist[i-1]+1:poslist[i]+1])
answerlist.append(down[poslist[i]+1:])
print (answerlist)
# [['a', 'b'], ['c', 'd', 'b'], ['e', 'r']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With