Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...