如何循环遍历列表? [英] How do I loop through a list by twos?

查看:42
本文介绍了如何循环遍历列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历 Python 列表并一次处理 2 个列表项.其他语言中的类似内容:

I want to loop through a Python list and process 2 list items at a time. Something like this in another language:

for(int i = 0; i < list.length(); i+=2)
{
   // do something with list[i] and list[i + 1]
}

实现这一目标的最佳方法是什么?

What's the best way to accomplish this?

推荐答案

您可以使用步长为 2 的范围:

You can use for in range with a step size of 2:

Python 2

for i in xrange(0,10,2):
  print(i)

Python 3

for i in range(0,10,2):
  print(i)

注意:在 Python 2 中使用 xrange 而不是 range,因为它更高效,因为它生成可迭代对象,而不是整个列表.

Note: Use xrange in Python 2 instead of range because it is more efficient as it generates an iterable object, and not the whole list.

这篇关于如何循环遍历列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆