python for loop步进值,python for循环,如何找到下一个值(对象)?

HI, I'm trying to use for loop to find the difference between every two object by minus each other.

So, how can I find the next value in a for loop?

for entry in entries:

first = entry # Present value

last = ?????? # The last value how to say?

diff = last = first

解决方案

It should be noted that none of these solutions work for generators. For that see Glenn Maynards superior solution.

use zip for small lists:

for current, last in zip(entries[1:], entries):

diff = current - last

This makes a copy of the list (and a list of tuples from both copies of the list) so it's good to use itertools for handling larger lists

import itertools as it

items = it.izip(it.islice(entries, 1, None), entries)

for current, last in items:

diff = current - last

This will avoid both making a copy of the list and making a list of tuples.

Another way to do it without making a copy is

entry_iter = iter(entries)

entry_iter.next() # Throw away the first version

for i, entry in enumerate(entry_iter):

diff = entry - entries[i]

And yet another way is:

for i in xrange(len(entries) - 1):

diff = entries[i+1] - entries[i]

This creates an iterator that indexes entries and advances it by one. It then uses enumerate to get an indice with the item. The indice starts at 0 and so points to the previous element because we the loop one item in.

Also, as Tyler pointed out in the comment, a loop might be overkill for such a simple problem if you just want to iterate over the differences.

diffs = (current - last for current, last in

it.izip(it.islice(entries, 1, None), entries))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值