Skip to content Skip to sidebar Skip to footer

Python Keeping Track Of Indices In Lists At Certain Points

I'm having some trouble with iteration and keeping track of various indices and values at different points in my list (I'm new to Python). I am running a series of cycles, but want

Solution 1:

I divide up the task, build a dictionary, D of the increasing sequences

c=[0,10,11,48,50.5,0.48,17,18,23,29,33,34.67,50.1,0.09,7,41,45,50]

D, k ={0:[]},0for i,(first, second)in enumerate(zip(c,[0]+c)):if first >= second:
        D[k].append((i, first))# adding increasing to value list in current D[k]else:
        k +=1
        D[k]=[(i, first)]# initializing new D[k] for next sequence

then print in the desired format

for k in D:  # sorted(D) safer, dict doesn't guarantee ordering, works here  print('C {0}:'.format(k))
    print('Start {0}'.format(D[k][0]))
    print('End   {0}'.format(D[k][-1]), '\n')

C 0:
Start (0, 0)
End   (4, 50.5) 

C 1:
Start (5, 0.48)
End   (12, 50.1) 

C 2:
Start (13, 0.09)
End   (17, 50) 

to print the dict D nicely in my IDE I needed wider line limit

import pprint

pp = pprint.PrettyPrinter(width=100)
pp.pprint(D)

{0: [(0, 0), (1, 10), (2, 11), (3, 48), (4, 50.5)],
 1: [(5, 0.48), (6, 17), (7, 18), (8, 23), (9, 29), (10, 33), (11, 34.67), (12, 50.1)],
 2: [(13, 0.09), (14, 7), (15, 41), (16, 45), (17, 50)]}

Solution 2:

Assuming your start value is the minimum value of the list and the end value is the maximum value of the list here's one way to do it:

(start_val,end_val)=(min(c),max(c))(start_ind,end_ind)=(c.index(start_val),c.index(end_val))

This also assumes that the min and max values don't have duplicates or if they have, you are ok with getting the index of the first, since the index() function only returns the index of the first element it finds equal to the argument. For more info: https://docs.python.org/3.6/library/stdtypes.html#typesseq

Solution 3:

Your list has increasing sequences so changes are located where a number is greater than its next. To compare all consecutive pairs of a list, you could use zip like here: Iterate over all pairs of consecutive items from a given list

Also to keep track of the list index, you can use enumerate

So here is a way to get index/value for all the start/end positions.

circle=0for i, (first,second) inenumerate(zip(c, c[1:])):
    if i==0:
        circle +=1print("\nC", circle, "\nStart:", i, first)
    elif i==len(c)-2:
        print("End:", i+1, second)
    elif first > second:
        print("End:", i, first)
        circle +=1print("\nC", circle, "\nStart:", i+1, second)

output:

C 1 
Start: 0 0End: 4 50.5

C 2 
Start: 5 0.48End: 12 50.1

C 3 
Start: 13 0.09End: 17 50

Post a Comment for "Python Keeping Track Of Indices In Lists At Certain Points"