The enumerate function accepts an object that can be traversed, such as a list, a string, which can traverse both subscript (index) and element value (value)
>>> a = ['AAA','BBB','CCC', 1235]>>>Print(a) ['AAA','BBB','CCC', 1235]>>>Print(Len (a))4>>> forIinchRange (len (a)):Print(i) 0123>>> forJinchRange (len (a)):Print(J,a[j]) 0 AAA1BBB2CCC3 1235>>> forI,jinchEnumerate (a):Print(i,j) 0 AAA1BBB2CCC3 1235>>> forXinchEnumerate (a):Print(x) (0,'AAA')(1,'BBB')(2,'CCC')(3, 1235)>>>
Use the enumerate function to count the number of lines of text:
Text content: Test.txt
This
Is
A
Test
Code:
for in Enumerate (open (R'I:\PythonTest\1234.txt','r' ): +=1 print(count)
Example 2:
text content:1234.txt
the Zen of Python, by Tim petersbeautiful isbetter than ugly. Explicit isbetter than implicit. Simple isBetter than Complex.complex isbetter than complicated. Flat isbetter than nested. Sparse isbetter than dense. Readability counts. Special cases aren'T special enough to break the rules.Although practicality beats purity. Errors should neverPasssilently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- andPreferably only one--obvious-do it. Although that, may notBe obvious at first unless're Dutch.Now isbetter than never. Although never isOften better than *right*Now . If the implementation isHard to explain, it's a bad idea.If the implementation isEasy to explain, it is a good idea. Namespaces is one honking great idea-Let's do more than those!
Code:
>>> for Count,line in enumerate (open (R ' I:\PythonTest\1234.txt ', ' R ')): Count +=1print (Count,line) Results: 1 the Zen of Python, by Tim Peters2 3 Beautiful are better than ugly.4 Explicit is better than implicit.5 simple is better than C Omplex.6 Complex is better than Complicated.7 Flat are better than Nested.8 Sparse is better than dense.9 readability count s.10 Special cases aren ' t special enough to break the rules.11 although practicality beats purity.12 Errors should never p silently.13 unless explicitly silenced.14 in the face of ambiguity, refuse the temptation to guess.15 there should is one--and preferably only one--obvious-to-do it.16 although this-a-do-not-be-obvious at first unless you ' re Dutch. Better than never.18 Although never is often better than *right* now.19 If the implementation are hard to explain , it's a bad idea.20 If the implementation was easy to explain, it could be a good idea.21 namespaces was one honking great I DEA-let's do more of those!≫>>
Python Enumerate function