Way to iterate two items at a time in a list?

。_饼干妹妹 提交于 2019-12-05 06:45:09

You can use the following method for grouping items from an iterable, taken from the documentation for zip():

connections = cmds.listConnections()
for destination, source in zip(*[iter(connections)]*2):
    print source, destination

Or for a more readable version, use the grouper recipe from the itertools documentation:

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

All, Great question & answer. I'd like to provide another solution that should compliment Andrew Clark's answer (props for using itertools!). His answer returns each value once like this:

iterable = [0, 1, 2, 3, 4, 5, 6,...] n = 2 grouper(n, iterable, fillvalue=None) --> [(0, 1), (2, 3), (3, 4), (5, 6),...]

In the code below each value will appear in n sub-sequences. Like this:

def moving_window(n, iterable):
  start, stop = 0, n
  while stop <= len(iterable):
      yield iterable[start:stop]
      start += 1
      stop += 1

--> [(0, 1), (1, 2), (2, 3), (3, 4),...]

A common application for this type of 'moving window' or 'kernel' is moving averages in the sciences and finance.

Also note that the yield statement allows each sub-sequence to be created as it's needed and not stored in memory.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!