获取对列表Python

que*_*sis -3 python list python-2.7

c = [1,2,3,4,5,6,7,8,9,10]

for a,b in func(c):
    doSomething()
Run Code Online (Sandbox Code Playgroud)

所以func()必须返回 (1,2) (2,3) (3,4) ... (8,9) (9,10)

在python 2.7中是否有一个优雅的方法来实现这一目标?

Ale*_*lli 6

当然,有很多方法。最简单:

def func(alist):
    return zip(alist, alist[1:])
Run Code Online (Sandbox Code Playgroud)

这会在 Python 2 中花费大量内存,因为zip它生成了一个实际列表,切片也是如此。有几种替代方案专注于提供内存节省的生成器,例如非常简单的:

def func(alist):
    it = iter(alist)
    old = next(it, None)
    for new in it:
        yield old, new
        old = new
Run Code Online (Sandbox Code Playgroud)

或者您可以更巧妙地部署强大的功能itertools,如pairwise@HughBothwell 提出的秘诀。


Hug*_*ell 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)
Run Code Online (Sandbox Code Playgroud)

然后

for a,b in pairwise(c):
    doSomething(a, b)
Run Code Online (Sandbox Code Playgroud)