python for循环,如何找到下一个值(对象)? [英] python for loop, how to find next value(object)?

查看:1833
本文介绍了python for循环,如何找到下一个值(对象)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用for循环找到每两个对象之间的差异减去彼此。
所以,如何找到for循环中的下一个值?

 用于输入条目:
first = entry#现值
last = ?????? #最后一个值怎么说?
diff = last = first


解决方案

请注意,这些解决方案的 none 都适用于发电机。为此,请参阅Glenn Maynards高级解决方案。



使用小型列表中的zip:

 当前,最后一个zip(条目[1:],条目):
diff = current - last

这个列表的副本(以及列表的两个副本中的一个元组列表)的副本,所以最好使用itertools来处理更大的列表。

  import itertools as 

items = it.izip(it.islice(entries,1,None),entries)
for current,last在项目中:
diff = current - last

这样可以避免复制list 创建一个元组列表。



另一种不复制的方法是

  entry_iter = iter(entries)
entry_iter.next()#丢弃第一个版本
for i,enumerate(entry_iter):
diff = entry - entries [i]

另一种方法是:

  for xrange(len(entries) -  1):
diff = entries [i + 1] - entries [i]

这将创建一个迭代器,索引条目,并将其前进1。然后使用 enumerate 来获得该项目的指示。而且,正如Tyler在评论中指出的那样,一个循环可能会过度杀伤对于这样一个简单的问题,如果你只是想迭代差异。

  diffs =(current  -  last for current,last in 
it.izip(it.islice(entries,1,None),entries))


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))

这篇关于python for循环,如何找到下一个值(对象)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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