使用for循环时如何获取上一个元素? [英] How to get the previous element when using a for loop?

查看:465
本文介绍了使用for循环时如何获取上一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
Python-循环中的上一个和下一个值
python for循环,如何查找下一个值(对象)?

Possible Duplicates:
Python - Previous and next values inside a loop
python for loop, how to find next value(object)?

我有一个包含很多元素的列表,我使用for循环遍历该列表.例如:

I've got a list that contains a lot of elements, I iterate over the list using a for loop. For example:

li = [2, 31, 321, 41, 3423, 4, 234, 24, 32, 42, 3, 24, 31, 123]

for i in li:
    print(i)

但是我想获得i之前的元素.我该如何实现?

But I want to get the element before i. How can I achieve that?

推荐答案

通常,您使用 enumerate() range() 即可通过元素.这是使用 zip()

Normally, you use enumerate() or range() to go through the elements. Here's an alternative using zip()

>>> li = [2, 31, 321, 41, 3423, 4, 234, 24, 32, 42, 3, 24, 31, 123]
>>> list(zip(li[1:], li))
[(31, 2), (321, 31), (41, 321), (3423, 41), (4, 3423), (234, 4), (24, 234), (32, 24), (42, 32), (3, 42), (24, 3), (31, 24), (123, 31)]

每个元组的第二个元素是列表的前一个元素.

the 2nd element of each tuple is the previous element of the list.

这篇关于使用for循环时如何获取上一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆