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

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

问题描述


可能重复:

什么是最pythonic方式遍历一个大块的列表?


我想通过循环Python列表并处理2个列表项。类似于另一种语言:

  for(int i = 0; i< list.length(); i + = 2 )
{
//用list [i]和list [i + 1]
}做一些事情

完成此操作的最佳方法是什么? 解决方案

步长为2:

Python 2

 <$ (0,10,2):
print(i)



我在范围(0,10,2):
print(i)

注意:在Python 2中使用xrange范围,因为它更有效,因为它生成一个可迭代的对象,而不是整个列表。

Possible Duplicate:
What is the most “pythonic” way to iterate over a list in chunks?

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?

解决方案

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)

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天全站免登陆