Is there any pythonic way to find the first coincidence before a giving index?
For example I want to find the 2
that go before the 1
, and the the 2
that go after the 1
.
a = [0,2,0,0,1,0,0,2,0]
for the 2
that go after the 1 I use this a.index(2,4)
.
Is there any easy or clean way to do it?
You can reverse the list and calculate the index of your "pivot" element in the reversed list, then use index
as normal:
def find_before(lst, e, idx):
new_idx = len(lst) - idx - 1
return len(lst) - lst[::-1].index(e, new_idx) - 1
It's worth noting that this is a bad idea for huge lists because it temporarily creates a copy when it reverses it. A better idea for that scenario is what blhsing did, which is just stepping backwards through the list:
def find_before(lst, e, idx):
i = idx
while i > 0:
i -= 1
if lst[i] == e:
return i
else:
raise ValueError(f"No element {e} found before index {idx}")
You just have to do it yourself since there's no built-in function for the equivalent of str.rindex
for lists:
def rindex(lst, x, start=-1, end=0):
if start < 0:
start += len(lst)
i = start
while i >= end and lst[i] != x:
i -= 1
if i < 0:
raise ValueError()
return i
a = [0,2,0,0,1,0,0,2,0]
print(rindex(a, 2, 4))
This outputs:
1
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