python - 在 Python 3 中实现 Pythonic "i, j"风格的 for 循环?

标签 python python-3.x

在 Python 中实现 C 风格“i, j”for 循环的优雅 Pythonic 解决方案是什么?这是一个循环示例:

for (i = 0, j = list.length - 1; i < list.length; j = i++ ){
    // Do stuff
}

我现在遇到了一些场景,我发现这种类型的循环很有用。然而,我似乎找不到一个优雅且Pythonic的解决方案来解决这个问题。

最佳答案

在 python 中,你可以只跟踪前一个元素:

previous = lst[-1]           # j = len(lst) - 1
for current in lst:          # i = 0; i < len(lst); i++
    print current, previous  # lst[i], lst[j]
    # do stuff
    previous = current       # j = i before incrementing

这里当前范围是lst[0]lst[-1],并且上一个开始使用lst[-1],然后通过lst[0]“跟踪”当前lst[-2].

在 Python 中,您很少需要对索引进行循环,请尝试直接对可迭代对象进行循环。

关于python - 在 Python 3 中实现 Pythonic "i, j"风格的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31767588/

相关文章:

Python:复制 `array.array`

python - 如何使用 Python 3 将照片上传到 Facebook

python - 我在运行一个简单的 pyttsx3 示例时遇到错误

django - 安装pipenv导致pip3无法使用

python - 最大小费计算器 - 天真的解决方案

python - Crontab - Python 脚本运行,将输出发送到邮件,但不写入文件

python - 执行 for 循环的最佳方法是什么?

python - 如何在包中包含示例或测试程序?

python - YouTube-dl 从 Reddit 下载并命名视频

python - 按以下方式划分列表