比较列表中所有相邻元素的Pythonic方法(Pythonic way of comparing all adjacent elements in a list)

编程入门 行业动态 更新时间:2024-10-28 10:22:10
比较列表中所有相邻元素的Pythonic方法(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]是否在一定范围内,或者它们是否相等。 或者,也许我想要做一些元素的“涓滴”。 越一般,越好。

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可以让你组合多个迭代器:

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.

更多推荐

本文发布于:2023-08-01 18:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1364854.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   方法   列表中   elements   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!