I have an array of integers derived from a gradient of a line. The array is called sign_slope and looks like this:
sign_slope = array([-1, 1, -1, ..., -1, -1, -1])
I am searching for the cases whereby consecutive items within the array are: 1, -1
For example you can see from the above output of sign_slope that:
sign_slope[1] = 1 and sign_slope[2] = -1
This would be the first case of many that I would like to detect item/index numbers for. I would like the code to output an array or list of index numbers corresponding to the (n-1)’th index i.e. sign_slope[1] in the above case.
I have written the below printing statement which appears to work. However, I do not know how to output the index numbers rather than the values as currently is the case and append them to a list or input them into an array.
for n in range(0, len(sign_slope)):
if sign_slope[n] < 0 and sign_slope[n - 1] > 0:
print sign_slope[n - 1]
else:
print 0
Thanks is advance,
Kane
Looping over a range of indicies is generally considered very unpythonic. It reads very poorly and masks what you are really trying to do. As such, a better solution to finding your sublist is to loop through using the
enumerate()builtin to get the indicies alongside the values. We can also provide a much more generic solution, and make it a generator which makes it easy to use.What we do here is loop through the list, taking the indicies where the value matches the beginning of our sublist. We then check to see if that segment of the list matches our sublist, if it does, we
yieldthe index. This allows us to quickly find all matching sublists in a list.We can then use this like so, using the
listbuiltin to create a list from the generator: