简体   繁体   English

Python-枚举索引

[英]Python - index in enumerate

I am just starting to learn Python. 我才刚刚开始学习Python。 At what index value in python does a for loop start from? for循环从python中的哪个索引值开始?

For example, if I have a text file with 390 lines, and I iterate: 例如,如果我有一个390行的文本文件,并且进行了迭代:

for i, word in enumerate(f)

Does the value of the index start from 0 or from 1 ? 索引的值是从0还是从1 Also, if I want to print out every 30th line in the file, then will I have to iterate like this? 另外,如果我想打印出文件中的第30行,那么我是否需要像这样进行迭代?

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. 当您使用带有列表的for循环时。 It includes all the elements in the list starting from the zero'th: if f=['x','y','z'] 它包括列表中从第零个开始的所有元素:如果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. 每30行打印一次。 You can use 您可以使用

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

which would output: 0, 30 ,60 90, ... 它将输出:0,30,60 90,...

For your first question: the index starts at 0 , as is generally the case in Python. 对于第一个问题:索引从0开始,这在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 % : 对于第二个问题:处理每30行打印一个更好的方法是使用mod运算符%

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). 这比测试range成员资格稍好,因为您不必担心边缘效应(即, range提供了一个在右端打开的半开间隔)。

From Python Docs : 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. Python的for语句按照它们在序列中出现的顺序遍历任何序列(列表或字符串)的项目。

So it will iterate in the specified range. 因此它将在指定范围内迭代。 To get the range [30, 60, ... 390] . 得到范围[30, 60, ... 390] You can try using the built-in function range or xrange (which yields element by element): 您可以尝试使用内置函数rangexrange (逐个元素生成):

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'])) . 回答有关索引0还是1开始的问题,尝试打印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' . i将遍历0, 1, 2并遍历'a', 'b', 'c' element

Using your example above: 使用上面的示例:

If you open your python shell and type this: 如果您打开python shell并输入以下命令:

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. 因此,要回答您的问题,它从索引0开始。对于第二个问题,您可以使用readlines()方法并在第30次迭代中打印。

By default, enumerate() starts at 0. If you want to start at one, pass it a second parameter at which you want to start: 默认情况下,enumerate()从0开始。如果要从1开始,请向其传递要从其开始的第二个参数:

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. 如果要每30行打印一次,这是一种简单的方法。

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?" 如果您不知道'%'(mod)运算符,则'i%30 == 0'就像在问“将i除以30后的余数是否为零?”

Python has its own std lib to do that: using fileinput Python有其自己的std lib:使用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 顺便说一句,如果您使用枚举,则索引从0开始,因此在测试时,您应该测试(n + 1) % 30 == 0 #其中n是当前索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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