Reputation: 51
I am trying to figure out a way to find whether all the integers in my list are increasing sequentially. If any numbers are non-sequential I want to get the index.
mylist = [1,2,3,2]
So, is 2 more than 1 (yes), is 3 more than 2 (yes), is 2 more than 3(no, get index).
I can compare an unsorted list against a sorted list to work out if it is sequential, but I also want to establish the index. Is there a way to do this?
Thanks Toby
Upvotes: 0
Views: 1170
Reputation: 76867
You can use enumerate
to do this for you:
In [1]: mylist = [1,2,3,2]
In [2]: for idx, element in enumerate(mylist):
...: if idx+1 != element:
...: print element, idx
...:
2 3
In case your sequence can start from any number,
In [1]: mylist = [2,3,4,2,7]
In [2]: for idx, element in enumerate(mylist):
....: if idx + mylist[0] != element:
....: print element, idx
....:
2 3
7 4
Upvotes: 1
Reputation: 8709
I guess you are looking for something like this:
>>> mylist = [1,2,3,2,3,5,6,3,7,8,6]
>>> [i+1 for i in range(len(mylist)-1) if mylist[i]>mylist[i+1]]
[3, 7, 10]
Upvotes: 1
Reputation: 706
This should do the trick:
def nonincr_index(l):
if not l:
return 0
prev=l[0]
for n,i in enumerate(l):
if i<prev:
return n
prev=i
return len(l)
>>> nonincr_index([1,2,3,2])
3
It returns the index of the non increasing item.
Upvotes: 1