How to use enumerate in this program?

谁都会走 提交于 2019-12-20 06:49:16

问题


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.



来源:https://stackoverflow.com/questions/33473827/how-to-use-enumerate-in-this-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!