使用for循环时如何获取前一个元素? [英] How to get the previous element when using a for loop?
本文介绍了使用for循环时如何获取前一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
Python - 循环中的上一个和下一个值
python for 循环,如何找到下一个值(对象)?
我有一个包含很多元素的列表,我使用 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?
推荐答案
您可以使用 <代码>邮政编码:
You can use zip
:
for previous, current in zip(li, li[1:]):
print(previous, current)
或者,如果您需要做一些更有趣的事情,因为创建列表或获取 li
的一部分将效率低下,请使用 pairwise
来自 itertools
or, if you need to do something a little fancier, because creating a list or taking a slice of li
would be inefficient, use the pairwise
recipe from itertools
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
for a, b in pairwise(li):
print(a, b)
这篇关于使用for循环时如何获取前一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文