我想知道是否有更多的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]是否在一定范围内,或者它们是否相等。 或者,也许我想要做一些元素的“涓滴”。 越一般,越好。
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 += 1I 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可以让你组合多个迭代器:
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的索引时才有可能。
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.
更多推荐
发布评论