在循环中使用Python

在循环中使用Python

本文介绍了在循环中使用Python for ..中的偏移量访问元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究Python,我发现使用它通常更好(或"pythonic")

I've been mucking around a bit with Python, and I've gathered that it's usually better (or 'pythonic') to use

for x in SomeArray:

而不是更C的风格

for i in range(0, len(SomeArray)):

我确实看到了好处,主要是更简洁的代码,以及使用漂亮的map()和相关功能的能力.但是,我经常遇到这样的情况:我想同时访问数组中不同偏移量的元素.例如,我可能想将当前元素添加到它后面的两个步骤中.有没有办法不借助显式索引来做到这一点?

I do see the benefits in this, mainly cleaner code, and the ability to use the nice map() and related functions. However, I am quite often faced with the situation where I would like to simultaneously access elements of varying offsets in the array. For example, I might want to add the current element to the element two steps behind it. Is there a way to do this without resorting to explicit indices?

推荐答案

在Python中执行此操作的方法是:

The way to do this in Python is:

for i, x in enumerate(SomeArray):
    print i, x

enumerate 生成器生成2个元组的序列,每个2元组包含数组索引和元素.

The enumerate generator produces a sequence of 2-tuples, each containing the array index and the element.

这篇关于在循环中使用Python for ..中的偏移量访问元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:12