遍历Python列表中的对项[duplicate]

时间:2022-03-08 19:28:19

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)?

在Python中是否可能以以下方式迭代列表(将此代码视为伪代码)?

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

And it should produce

它应该产生

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

5 个解决方案

#1


74  

From itertools receipes:

出现从itertools receipes:

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):
    ...

#2


77  

You can use the zip function:

你可以使用zip功能:

a = [5, 7, 11, 4, 5]
for v, w in zip(a[:-1], a[1:]):
    print [v, w]

#3


50  

To do that you should do:

要做到这一点,你应该:

a =  [5, 7, 11, 4, 5]
for i in range(len(a)-1):
    print [a[i], a[i+1]]

#4


7  

Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:

几乎一字不差地遍历Python中的列表(循环方式)中的对:

def pairs(seq):
    i = iter(seq)
    prev = next(i)
    for item in i:
        yield prev, item
        prev = item

#5


4  

>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
...     print a[n],a[n+1]
...
5 7
7 11
11 4
4 5

#1


74  

From itertools receipes:

出现从itertools receipes:

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):
    ...

#2


77  

You can use the zip function:

你可以使用zip功能:

a = [5, 7, 11, 4, 5]
for v, w in zip(a[:-1], a[1:]):
    print [v, w]

#3


50  

To do that you should do:

要做到这一点,你应该:

a =  [5, 7, 11, 4, 5]
for i in range(len(a)-1):
    print [a[i], a[i+1]]

#4


7  

Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:

几乎一字不差地遍历Python中的列表(循环方式)中的对:

def pairs(seq):
    i = iter(seq)
    prev = next(i)
    for item in i:
        yield prev, item
        prev = item

#5


4  

>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
...     print a[n],a[n+1]
...
5 7
7 11
11 4
4 5