A pythonic way of comparing all adjacent elements in a list

I want to know if there is a more Pythonic way to do the following:

A = some list
i = 0
j = 1
for _ in range(1, len(A)):
    #some operation between A[i] and A[j]
    i += 1
    j += 1

I feel this should / could be done differently. Ideas?

EDIT: Because some are requesting requirements. I need a general answer. It is possible to verify that A [i], A [j] are between a certain range or if they are equal. Or maybe I wanted to make a "trickle" of elements. The more general, the better.

+4
source share
5 answers

zip allows you to combine several iterators:

for i,j in zip(range(0,len(A)-1), range(1,len(A))):
    #some operation between A[i] and A[j]

you can also use enumeratefor a range object:

for i,j in enumerate(range(1,len(A)):
    #some operation between A[i] and A[j]

, A, , , A[i] A[j], , :

A = list(range(10))
found1=True
while found1:
    found1=False
    for i,j in enumerate(range(1,len(A))):
        if A[i] < A[j]:
            A[i],A[j] = A[j],A[i]
            found1=True
print(A)

, A.

+1

itertools. , .

from itertools import tee

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

for current, next_ in pairwise(A):
    # do something
    pass

, enumerate .

for current_index, (current, next_) in enumerate(pairwise(A)):
    # do something
    pass
+7

"+":

A = [A[i+1]+A[i] for i in range(len(A)-1)]

:

A = [operation(A[i], A[i+1]) for i in range(len(A)-1)]
+3

:

A = some list
for Ai, Aj in zip(A, A[1:]):
    #some operation between A[i] and A[j]
0
from itertools import islice
A1 = iter(A)
A2 = islice(A, 1, None)
for a1, a2 in zip(A1, A2):
    # do whatever with A[i], A[i+1]

islice , A[1:] ( ). , None , islice(iterable, stop) stop ( ), , . ( None), .

islice(iterable, start, stop[, step])  # roughly = iterable[start:stop:step]
islice(iterable, stop)                 # roughly = iterable[:stop]

, .

zip() , shortest (A2). IndexError IndexError.

0

All Articles