如何一次迭代列表中的两个项目?

编程入门 行业动态 更新时间:2024-10-25 08:14:37
本文介绍了如何一次迭代列表中的两个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道是否有更好的方法可以一次遍历列表中的两个项目.我经常使用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, 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)

更多推荐

如何一次迭代列表中的两个项目?

本文发布于:2023-11-28 22:42:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644235.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   迭代   项目   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!