[Python] Way to iterate two items at a time in a list?

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página