如何一次迭代列表中的两个项目? [英] Way to iterate two items at a time in a list?

查看:82
本文介绍了如何一次迭代列表中的两个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法可以一次遍历列表中的两个项目.我经常使用Maya,并且其中一个命令(listConnections)返回交替值的列表.该列表看起来像[connectionDestination,connectionSource,connectionDestination,connectionSource].要对该列表执行任何操作,理想情况下,我想执行以下操作:

for destination, source in cmds.listConnections():
    print source, destination

当然,您可以使用[:: 2]迭代列表中的所有其他项目,枚举和源将是index + 1,但是随后您必须为奇数列表和其他内容添加额外的检查. /p>

到目前为止,我想出的最接近的东西是:

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

这并不是超级重要,因为我已经有做自己想做的方法.这似乎是应该有一种更好的方法来做的事情之一.

解决方案

您可以使用以下方法对可迭代项进行分组,该方法取自石斑鱼食谱:

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)

I am wondering if there is a better way to iterate two items at a time in a list. I work with Maya a lot, and one of its commands (listConnections) returns a list of alternating values. The list will look like [connectionDestination, connectionSource, connectionDestination, connectionSource]. To do anything with this list, I would ideally like to do something similar to:

for destination, source in cmds.listConnections():
    print source, destination

You could, of course just iterate every other item in the list using [::2] and enumerate and source would be the index+1, but then you have to add in extra checks for odd numbered lists and stuff.

The closest thing I have come up with so far is:

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

This isn't super important, as I already have ways of doing what I want. This just seems like one of those things that there should be a better way of doing it.

解决方案

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)

这篇关于如何一次迭代列表中的两个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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