How to use enumerate in this program?

2019-03-03 09:44发布

问题:

f=open('Student.dat','r+') # opens Student.dat file
roll1=input("Enter roll to be found") # to find a record in a list using a roll no
rec=f.readlines()
for i,lst in enumerate(rec):
        if lst == roll1:
            print rec[i]

Is this the proper way to use enumerate?? or should i use another loop within??

回答1:

Here enumerate doesn't help much; you could use instead (which would be simpler and clearer):

for i in rec:
    if i == roll1:
        print i

enumerate is useful when you really need to get at the same time values and indices, which doesn't seem to be the case here. (In your piece of code rec[i] does the same thing than lst; thus if you really want to use enumerate you should replace it.)

By the way, you should add better tags to your question, at least python.