Python 在列表中一次迭代两个项目的方法?

Python 在列表中一次迭代两个项目的方法?,python,maya,Python,Maya,我想知道是否有更好的方法在列表中一次迭代两个项目。我经常使用Maya,它的一个命令(listConnections)返回一个交替值列表。该列表类似于[connectionDestination,connectionSource,connectionDestination,connectionSource]。要使用此列表执行任何操作,我理想情况下希望执行以下类似操作: for destination, source in cmds.listConnections(): print sour

我想知道是否有更好的方法在列表中一次迭代两个项目。我经常使用Maya,它的一个命令(listConnections)返回一个交替值列表。该列表类似于[connectionDestination,connectionSource,connectionDestination,connectionSource]。要使用此列表执行任何操作,我理想情况下希望执行以下类似操作:

for destination, source in cmds.listConnections():
    print source, destination
当然,您可以使用[::2]迭代列表中的其他每一项,并且enumerate和source将是索引+1,但是您必须添加奇数列表和其他内容的额外检查

到目前为止,我想到的最接近的事情是:

from itertools import izip
connections = cmds.listConnections()
for destination, source in izip(connections[::2], connections[1::2]):
    print source, destination

这并不是特别重要,因为我已经有办法做我想做的事了。这似乎是应该有更好的方法来完成的事情之一。

您可以使用以下方法从iterable中对项目进行分组,该方法取自的文档:

或者,对于更可读的版本,请使用itertools文档中的:

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)
全部,, 很好的问题和答案。我想提供另一个解决方案,这应该是对Andrew Clark的回答(使用itertools的道具!)的补充。他的答案返回每个值一次,如下所示:

iterable=[0,1,2,3,4,5,6,…]
n=2
石斑鱼(n,iterable,fillvalue=None)
-->[(0,1),(2,3),(3,4),(5,6),…]

在下面的代码中,每个值将以n个子序列出现。像这样:

def moving_window(n, iterable):
  start, stop = 0, n
  while stop <= len(iterable):
      yield iterable[start:stop]
      start += 1
      stop += 1
def移动_窗口(n,iterable):
开始,停止=0,n
停止时[(0,1)、(1,2)、(2,3)、(3,4),…]

这种“移动窗口”或“内核”的常见应用是科学和金融领域的移动平均值


还要注意,yield语句允许根据需要创建每个子序列,而不是存储在内存中

看看这篇文章,也许它也会有所帮助,你所拥有的似乎是一个很好的方法。行吗?哦,哇。我花了一点时间才弄明白
grouper()
是如何工作的。我们构建
args
列表,以便所有args都是对单个迭代器的引用;因此,当
itertools.izip_longest()
尝试从每个序列中提取一个值时,实际上是从同一迭代器中提取下一个值!优雅高效!
def moving_window(n, iterable):
  start, stop = 0, n
  while stop <= len(iterable):
      yield iterable[start:stop]
      start += 1
      stop += 1