遍历Python列表中的项目对 [英] Iterate through pairs of items in a Python list

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

问题描述

可能的重复项:
在Python中将列表作为对(当前,下一个)进行迭代
迭代列表中的每两个元素

Possible Duplicates:
Iterate a list as pair (current, next) in Python
Iterating over every two elements in a list

是否可以在Python中以以下方式迭代列表(将此代码作为伪代码进行处理)?

Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)?

a = [5, 7, 11, 4, 5]
for v, w in a:
    print [v, w]

它应该产生

[5, 7]
[7, 11]
[11, 4]
[4, 5]

推荐答案

来自 itertools 的记录:

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

for v, w in pairwise(a):
    ...

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

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