我有教程中的代码可以执行此操作:
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
但是,如果我只想从 elements[0] 打印到 elements[4],这是如何实现的?
最佳答案
这可以使用切片来实现:
for i in elements[0:5]:
print "Element was: %d" % i
结束索引不包含在范围内,因此您需要将它从 4 增加到 5。
起始零可以省略:
for i in elements[:5]:
print "Element was: %d" % i
有关详细信息,请参阅 Explain Python's slice notation
关于python - 遍历数组的部分部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812172/