I want to know if there's a more Pythonic way of doing 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 like this should/could be done differently. Ideas?
EDIT: Since some are asking for requirements. I wanted a general-purpose answer. Maybe to check if A[i], A[j] are between a certain range, or if they're equal. Or maybe I wanted to do a "trickle-up" of elements. The more general, the better.
zip
lets you combine multiple 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 enumerate
on a range object:
for i,j in enumerate(range(1,len(A)):
#some operation between A[i] and A[j]
Note that unlike the other answers this gives you access to the indices of A not just the items, this is necessary if you want to use any assignment to A[i]
or A[j]
, for example here is a very basic bubble sort:
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)
this is only possible when you iterate over the indices of A.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments