我想知道是否有更好的方法可以一次遍历列表中的两个项目.我经常使用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这并不是超级重要,因为我已经有做自己想做的方法.这似乎是应该有一种更好的方法来做的事情之一.
解决方案您可以使用以下方法对可迭代项进行分组,该方法取自 zip() :
connections = cmds.listConnections() for destination, source in zip(*[iter(connections)]*2): print source, destination或者对于更具可读性的版本,请使用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)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, destinationYou 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, destinationThis 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, destinationOr 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)
更多推荐
如何一次迭代列表中的两个项目?
发布评论