37

问题很简单,我想迭代列表的每个元素和下一个成对的元素(用第一个包裹最后一个)。

我考虑过两种非pythonic的方法:

def pairs(lst):
    n = len(lst)
    for i in range(n):
        yield lst[i],lst[(i+1)%n]

和:

def pairs(lst):
    return zip(lst,lst[1:]+[lst[:1]])

预期输出:

>>> for i in pairs(range(10)):
    print i

(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
(7, 8)
(8, 9)
(9, 0)
>>> 

关于更pythonic的方法有什么建议吗?也许有一个我没有听说过的预定义功能?

还有一个更一般的 n-fold(三重奏、四重奏等,而不是对)版本可能会很有趣。

4

13 回答 13

30
def pairs(lst):
    i = iter(lst)
    first = prev = item = i.next()
    for item in i:
        yield prev, item
        prev = item
    yield item, first

适用于任何非空序列,无需索引。

于 2009-08-10T21:57:01.947 回答
9

我已经为自己编写了元组通用版本,我喜欢第一个版本,因为它简洁优雅,我看的越多,我就越觉得它是 Pythonic……毕竟,有什么比一个带 zip 的衬里更 Pythonic ,星号参数扩展,列表推导,列表切片,列表连接和“范围”?

def ntuples(lst, n):
    return zip(*[lst[i:]+lst[:i] for i in range(n)])

即使对于大型列表,itertools 版本也应该足够高效......

from itertools import *
def ntuples(lst, n):
    return izip(*[chain(islice(lst,i,None), islice(lst,None,i)) for i in range(n)])

以及不可索引序列的版本:

from itertools import *
def ntuples(seq, n):
    iseq = iter(seq)
    curr = head = tuple(islice(iseq, n))
    for x in chain(iseq, head):
        yield curr
        curr = curr[1:] + (x,)

不管怎样,谢谢大家的建议!:-)

于 2009-08-10T22:37:22.583 回答
6

我一如既往地喜欢 tee:

from itertools import tee, izip, chain

def pairs(iterable):
    a, b = tee(iterable)
    return izip(a, chain(b, [next(b)]))
于 2012-03-27T07:32:21.293 回答
5

这可能是令人满意的:

def pairs(lst):
    for i in range(1, len(lst)):
        yield lst[i-1], lst[i]
    yield lst[-1], lst[0]

>>> a = list(range(5))
>>> for a1, a2 in pairs(a):
...     print a1, a2
...
0 1
1 2
2 3
3 4
4 0

如果你喜欢这类东西,请查看wordaligned.org上的 python 文章。作者对python中的生成器情有独钟。

于 2009-08-10T22:00:18.883 回答
2

我会这样做(主要是因为我可以阅读此内容):

class Pairs(object):
    def __init__(self, start):
        self.i = start
    def next(self):
        p, p1 = self.i, self.i + 1
        self.i = p1
        return p, p1
    def __iter__(self):
        return self

if __name__ == "__main__":
    x = Pairs(0)
    y = 1
    while y < 20:
        print x.next()
        y += 1

给出:

(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
(7, 8)
(8, 9)
于 2009-08-10T23:08:30.370 回答
1
[(i,(i+1)%len(range(10))) for i in range(10)]

将 range(10) 替换为您想要的列表。

一般来说,“循环索引”在 python 中很容易;只需使用:

a[i%len(a)] 
于 2011-06-05T10:05:32.790 回答
0

要回答有关解决一般情况的问题:

import itertools

def pair(series, n):
    s = list(itertools.tee(series, n))
    try:
        [ s[i].next() for i in range(1, n) for j in range(i)]
    except StopIteration:
        pass
    while True:
        result = []
        try:
            for j, ss in enumerate(s):
                result.append(ss.next())
        except StopIteration:
            if j == 0:
                break
            else:
                s[j] = iter(series)
                for ss in s[j:]:
                    result.append(ss.next())
        yield result

输出是这样的:

>>> for a in pair(range(10), 2):
...     print a
...
[0, 1]
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 0]
>>> for a in pair(range(10), 3):
...     print a
...
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 0]
[9, 0, 1]
于 2009-08-10T22:27:19.813 回答
0

这无限循环,无论好坏,但在算法上非常清楚。

from itertools import tee, cycle

def nextn(iterable,n=2):
    ''' generator that yields a tuple of the next n items in iterable.
    This generator cycles infinitely '''
    cycled = cycle(iterable)
    gens = tee(cycled,n)

    # advance the iterators, this is O(n^2)
    for (ii,g) in zip(xrange(n),gens):
        for jj in xrange(ii):
            gens[ii].next()

    while True:
        yield tuple([x.next() for x in gens])


def test():
    data = ((range(10),2),
        (range(5),3),
        (list("abcdef"),4),)
    for (iterable, n) in data:
        gen = nextn(iterable,n)
        for j in range(len(iterable)+n):
            print gen.next()            


test()

给出:

(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
(7, 8)
(8, 9)
(9, 0)
(0, 1)
(1, 2)
(0, 1, 2)
(1, 2, 3)
(2, 3, 4)
(3, 4, 0)
(4, 0, 1)
(0, 1, 2)
(1, 2, 3)
(2, 3, 4)
('a', 'b', 'c', 'd')
('b', 'c', 'd', 'e')
('c', 'd', 'e', 'f')
('d', 'e', 'f', 'a')
('e', 'f', 'a', 'b')
('f', 'a', 'b', 'c')
('a', 'b', 'c', 'd')
('b', 'c', 'd', 'e')
('c', 'd', 'e', 'f')
('d', 'e', 'f', 'a')
于 2009-08-11T00:42:37.237 回答
0

Fortran 的 zip * range 解决方案的更短版本(这次使用 lambda;):

group = lambda t, n: zip(*[t[i::n] for i in range(n)])

group([1, 2, 3, 3], 2)

给出:

[(1, 2), (3, 4)]
于 2010-02-09T19:05:51.080 回答
0

这是一个支持可选起始索引的版本(例如,返回 (4, 0) 作为第一对,使用 start = -1:

import itertools

def iterrot(lst, start = 0):

    if start == 0:
        i = iter(lst)
    elif start > 0:
        i1 = itertools.islice(lst, start, None)
        i2 = itertools.islice(lst, None, start)
        i = itertools.chain(i1, i2)
    else:
        # islice doesn't support negative slice indices so...
        lenl = len(lst)
        i1 = itertools.islice(lst, lenl + start, None)
        i2 = itertools.islice(lst, None, lenl + start)
        i = itertools.chain(i1, i2)
    return i


def iterpairs(lst, start = 0):

    i = iterrot(lst, start)     

    first = prev = i.next()
    for item in i:
        yield prev, item
        prev = item
    yield prev, first


def itertrios(lst, start = 0):

    i = iterrot(lst, start)     

    first = prevprev = i.next()
    second = prev = i.next()
    for item in i:
        yield prevprev, prev, item
        prevprev, prev = prev, item

    yield prevprev, prev, first
    yield prev, first, second
于 2011-04-10T18:44:48.637 回答
0
def pairs(ex_list):
    for i, v in enumerate(ex_list):
        if i < len(list) - 1:
            print v, ex_list[i+1]
        else:
            print v, ex_list[0]

枚举返回一个带有索引号和值的元组。我打印列表的值和以下元素ex_list[i+1]。ifi < len(list) - 1表示如果 v不是列表的最后一个成员。如果是:打印 v 和列表的第一个元素print v, ex_list[0]

编辑:

你可以让它返回一个列表。只需将打印的元组附加到列表并返回即可。

def pairs(ex_list):
    result = []
    for i, v in enumerate(ex_list):
        if i < len(list) - 1:
            result.append((v, ex_list[i+1]))
        else:
            result.append((v, ex_list[0]))
    return result
于 2013-05-15T14:13:47.633 回答
0

当然,您始终可以使用deque

from collections import deque
from itertools import *

def pairs(lst, n=2):
    itlst = iter(lst)
    start = list(islice(itlst, 0, n-1))
    deq = deque(start, n)
    for elt in chain(itlst, start):
        deq.append(elt)
        yield list(deq)
于 2014-04-19T23:07:20.637 回答
-1
i=(range(10))

for x in len(i):
    print i[:2]
    i=i[1:]+[i[1]]

比这更 Pythonic 是不可能的

于 2011-01-04T01:59:53.710 回答