简体   繁体   中英

Python - index in enumerate

I am just starting to learn Python. At what index value in python does a for loop start from?

For example, if I have a text file with 390 lines, and I iterate:

for i, word in enumerate(f)

Does the value of the index start from 0 or from 1 ? Also, if I want to print out every 30th line in the file, then will I have to iterate like this?

if i+1 in [30,60,90,120,150,180,210,240,270,300,330,360,390]:
    print i
    ...

when you are using for loop with a list. It includes all the elements in the list starting from the zero'th: if f=['x','y','z']

for i, word in enumerate(f):
    print i, word

would output:

0 x
1 y
2 z

for printing every 30th line. You can use

for i in range(0,390,30):

which would output: 0, 30 ,60 90, ...

For your first question: the index starts at 0 , as is generally the case in Python. (Of course, this would have been very easy to try for yourself and see).

>>> x = ['a', 'b', 'c']
>>> for i, word in enumerate(x):
    print i, word


0 a
1 b
2 c

For your second question: a much better way to handle printing every 30th line is to use the mod operator % :

if i+1 % 30 == 0:
    print i
    # ...

This is slightly better than testing for membership in range since you don't have to worry about edge effects (ie since range gives a half-open interval that is open on the right end).

From Python Docs :

Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

So it will iterate in the specified range. To get the range [30, 60, ... 390] . You can try using the built-in function range or xrange (which yields element by element):

for i in range(30, 390 + 1, 30):  # range(start, end, step)
    print i

Answering the question about wheter the index starts from 0 or 1 , try printing tuple(enumerate(['a','b','c'])) . It looks like:

print tuple(enumerate(['a', 'b', 'c']))
>>> ((0, 'a'), (1, 'b'), (2, 'c'))

so when you do

for i, element in enumerate(['a', 'b', 'c']):

i will iterate over 0, 1, 2 and element over 'a', 'b', 'c' .

Using your example above:

If you open your python shell and type this:

for i, word in enumerate(f):
   print i, word

you see that the output will be:

0 30
1 60
2 90
3 120
4 150
5 180
6 210
7 240
8 270
9 300
10 330
11 360
12 390

So, to answer your question, it starts from index 0. As for the second question, you can use readlines() method and print on every 30th iteration.

By default, enumerate() starts at 0. If you want to start at one, pass it a second parameter at which you want to start:

for i, line in enumerate(f, 1):
    print i, line

If you want to print every 30th line, here is an easy way to do it.

for i, line in enumerate(f):
    if (i+1) % 30 == 0:
        print line

If you don't know the '%' (mod) operator, 'i % 30 == 0' is like asking "is the remainder zero after dividing i by 30?"

Python has its own std lib to do that: using fileinput

#!/usr/bin/python

import fileinput

for line in fileinput.input("txt.txt"):
    if fileinput.lineno() % 30 == 0:
        print fileinput.lineno(), line,

BTW if you are using enumerate, then the index start from 0, so when you test it you should test (n + 1) % 30 == 0 # where n is the current index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM