python - 遍历数组的部分部分

标签 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

但是,如果我只想从 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/

相关文章:

惰性可调用的 Python 依赖注入(inject)

python - python类声明中的对象参数

python - 如何从 child FK 中获取 parent ?

python - Tumblr API 2 : Where is the "OAUTH_TOKEN" and "OAUTH_TOKEN_SECRET"

python - 在 Python 中连接两个列表中的所有项目

python - 使用 if 语句确定 for 循环范围 - pandas.append 在循环中不起作用

python pandas数据框按日期条件切片

python - Pandas 根据日期加入

python - 在 Python 3.3.2 上使用 Pandas 0.12.0 和 Matplotlib 1.3.1 绘制包含 NaN 的 DataFrame 时出错

python - matplotlib tripcolor 给出长三角形