Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

What Does Enumerate Do in This Context [Python]

I know that there is another answer to this but that's for complex users. I'm a basic python user who started a couple of days ago. So I need a simple answer

Im trying to understand this line of code. Mostly the enumerate part. Could someone please what enumerate does.

f = open("solutions.txt", "r")
searchlines = f.readlines()
for i, line in enumerate(searchlines):

Thanks in Advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

enumerate is used to generate a line index, the i variable, together with the line string, which is the i-th line in the text file. Getting an index from an iterable is such a common idiom on any iterable that enumerate provides an elegant way to do this. You could, of course, just initialize an integer counter i and increment it after each line is read, but enumerate does that for you. The main advantage is code readability: the i variable initialization and increment statements would be book-keeping code that is not strictly necessary to show the intent of what that loop is trying to do. Python excels at revealing the business-logic of code being concise and to the point. You can look at Raymond Hettinger's presentation to learn more about idiomatic python from these excellent notes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...