使用for循环时如何获取上一个元素? [英] How to get the previous element when using a for loop?
本文介绍了使用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屋!
查看全文