for循环中的Python列表的连续索引,不指定索引

时间:2012-06-01 21:08:21

标签: python list iterator

我可以使用以下“Pythonic”语法遍历Python(v.2.6)列表而不指定索引:

the_list = [2, 3, 5, 7, 11, 13]
for item in the_list:
    print item + 2

但是如果我想对两个连续的索引执行操作,我想我必须指定索引号,并对for循环的范围进行相应的更改:

the_list = [2, 3, 5, 7, 11, 13]
for i in xrange(len(the_list)-1):
    print the_list[i] + the_list[i+1]

这是对的吗?或者有没有办法保持Pythonic并避免使用表达式xrange(len(the_list)-1)

1 个答案:

答案 0 :(得分:2)

我很喜欢itertools模块文档中列出的pairwise食谱:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

则...

for x, x_next in pairwise(the_list):
    ...

您也可以zip列出自己的一部分:

for x, x_next in zip(the_list, the_list[1:]):
    ...
相关问题