[英]Pythonic way of comparing all adjacent elements in a list
我想知道是否有更多的Pythonic方法來執行以下操作:
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
我覺得這應該/可以做得不同。 想法?
編輯:因為有些人要求要求。 我想要一個通用的答案。 也許檢查A [i],A [j]是否在某個范圍之間,或者它們是否相等。 或許我想做一個“涓涓細流”的元素。 越普遍越好。
為了做到這一點,在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
對於'+'操作:
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)]
zip
允許您組合多個迭代器:
for i,j in zip(range(0,len(A)-1), range(1,len(A))):
#some operation between A[i] and A[j]
你也可以在范圍對象上使用enumerate
:
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的索引時才有可能。
你可以這樣做:
A = some list
for Ai, Aj in zip(A, A[1:]):
#some operation between A[i] and A[j]
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
項(因此名稱),當第三個參數傳遞給它時,它與您想要的完全相反將第二個視為起始位置而不是停止索引。
islice(iterable, start, stop[, step]) # roughly = iterable[start:stop:step]
islice(iterable, stop) # roughly = iterable[:stop]
有關詳細信息,請參閱文檔 。
現在zip()
發出值,直到shortest
迭代器( A2
)耗盡。 所以不用擔心可能的IndexError
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.