Python 使用for循环时如何获取前一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4002598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:47:35  来源:igfitidea点击:

How to get the previous element when using a for loop?

pythonlistfor-loop

提问by user469652

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

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

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

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

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

for i in li:
    print(i)

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

但我想在i. 我怎样才能做到这一点?

回答by JoshD

Use a loop counter as an index. (Be sure to start at 1 so you stay in range.)

使用循环计数器作为索引。(一定要从 1 开始,这样你才能保持在范围内。)

for i in range(1, len(li)):
  print(li[i], li[i-1])

回答by Anurag Uniyal

Just keep track of index using enumerateand get the previous item by index

只需跟踪索引 usingenumerate并按索引获取上一项

li = list(range(10))

for i, item in enumerate(li):
    if i > 0:
        print(item, li[i-1])

print("or...")

for i in range(1, len(li)):
    print li[i], li[i-1]

Output:

输出:

1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
or...
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8

Another alternative is to remember the last item, e.g.

另一种选择是记住最后一项,例如

last_item = None
for item in li:
    print(last_item, item)
    last_item = item

回答by jMyles

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

counter = 0
for l in li:
    print l
    print li[counter-1] #Will return last element in list during first iteration as martineau points out.
    counter+=1

回答by ghostdog74

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

通常,您使用enumerate()range()来遍历元素。这是使用的替代方法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.

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

回答by SingleNegationElimination

You can use zip:

您可以使用zip

for previous, current in zip(li, li[1:]):
    print(previous, current)

or, if you need to do something a little fancier, because creating a list or taking a slice of liwould be inefficient, use the pairwiserecipe from itertools

或者,如果你需要做的东西有点票友,因为建立一个列表或者服用一片li是低效的,使用pairwise的配方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)

回答by kindall

j = None
for i in li:
    print(j)
    j = i

回答by Muhammad Alkarouri

An option using the itertoolsrecipe from here:

使用此处itertools食谱的选项:

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)

for i, j in pairwise(li):
    print(i, j)