简体   繁体   English

如何迭代/循环列表并引用前一个(n-1)元素?

[英]How to iterate/loop over a list and reference previous (n-1) element?

I need to iterate over a list and compare the current element and the previous element.我需要遍历一个列表并比较当前元素和前一个元素。 I see two simple options.我看到两个简单的选项。

1) Use enumerate and indexing to access items 1) 使用枚举和索引来访问项目

for index, element in enumerate(some_list[1:]):
    if element > some_list[index]: 
        do_something()

2) Use zip() on successive pairs of items 2) 在连续的项目对上使用 zip()

for i,j in zip(some_list[:-1], some_list[1:]):
    if j > i:
        do_something()

3) itertools 3)迭代工具

I personally don't like nosklo's answer from here, with helper functions from itertools我个人不喜欢nosklo 的回答,这里有 itertools 的辅助函数

So what is the way to go, in Python 3?那么在 Python 3 中要走的路是什么?

The zip method is probably the most commonly used, but an alternative (which may be more readable) would be: zip 方法可能是最常用的方法,但另一种方法(可能更具可读性)是:

prev = None
for cur in some_list:
   if (prev is not None) and (prev > cur):
       do_something()
   prev = cur

This will obviously not work if None can occur somewhere in some_list, but otherwise it does what you want.如果在 some_list 中的某处出现 None ,这显然不起作用,否则它会做你想要的。

Another version could be a variation on the enumerate method:另一个版本可能是 enumerate 方法的变体:

for prev_index, cur_item in enumerate(somelist[1:]):
    if somelist[prev_index] > cur_item:
        do_something()

Just be sure not to modify somelist in the loop or the results will be unpredictable.请确保不要在循环中修改 somelist 否则结果将是不可预测的。

You can use iter which avoids the need to index or slice:您可以使用 iter 避免索引或切片的需要:

it = iter(some_list)
prev = next(it)
for ele in it:
     if prev > ele:
         # do something
    prev = ele

There is also the pairwise recipe in itertools which uses tee: itertools 中还有使用 tee 的成对配方

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) # itertools.izip python2

for a,b in pairwise(some_list):
    print(a,b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM