Assigning count from enumerate

578 views Asked by At

I am fairly new to python, and I am trying to find out if it is possible to assign the count from enumerate to the variable it is with. At the moment I have something along the lines as.

for i, grb in enumerate(results):
           try:
                grb_date = (re.sub('[A-Z]','',grb.name))
                end_results = [i, grb_date]
                print (end_results)
           except:    
                print ('No name')
                pass

The output is like the below

[935, '120612']
[936, '120616']
[937, '120618']
[938, '120618']
[939, '120619']

The end goal is to basically have an input function that should equate the right number but I ultimately need the 'i' value (the left one) with the next part of the code. Is there a way to do this?

1

There are 1 answers

3
NDevox On

From what I understand from the comments below, you don't need to access the number from the last loop, but need it to access the id of the second column.

If that is the case I would use a dictionary:

data = {}

for i, grb in enumerate(results):
    try:
        grb_date = (re.sub('[A-Z]','',grb.name))
        end_results = [i, grb_date]
        data[str(i)] = grb_date  # this is the important bit
        print (end_results)
     except:    
        print ('No name')

Now you can reference the grb_date directly with the number (i):

while 1:
    attempt = input('enter the record you want: ')  # I'm assuming you are using Py 3.x, otherwise use raw_input
    try:
        print(data[attempt])
    except KeyError:
        print('ID does not exist')