循环遍历数组的部分部分

sta*_*tor 1 python

我有一个教程中的代码执行此操作:

elements = []

for i in range(0, 6):
    print "Adding %d to the list." % i
    # append is a function that lists understand
    elements.append(i)

for i in elements:
    print "Element was: %d" % i
Run Code Online (Sandbox Code Playgroud)

但是,如果我只想从元素[0]打印到元素[4],这是如何实现的?

在此先感谢您的反馈!

NPE*_*NPE 8

这可以使用切片来实现:

for i in elements[0:5]:
    print "Element was: %d" % i
Run Code Online (Sandbox Code Playgroud)

结束索引不包含在范围内,因此您需要将其从4增加到5.

起始零点可以省略:

for i in elements[:5]:
    print "Element was: %d" % i
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅解释Python的切片表示法