iterating over two values of a list at a time in python

PythonList

Python Problem Overview


I have a set like (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08) which I need to iterate over, like

    for x,y in (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08)
        print (x,y)

which would print

    669256.02 6117662.09
    669258.61 6117664.39
    669258.05 6117665.08

im on Python 3.3 btw

Python Solutions


Solution 1 - Python

You can use an iterator:

>>> lis = (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08)
>>> it = iter(lis)
>>> for x in it:
...     print (x, next(it))
...     
669256.02 6117662.09
669258.61 6117664.39
669258.05 6117665.08

Solution 2 - Python

>>> nums = (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08)
>>> for x, y in zip(*[iter(nums)]*2):
	    print(x, y)

	
669256.02 6117662.09
669258.61 6117664.39
669258.05 6117665.08

Solution 3 - Python

The grouper example in the itertools recipes section should help you here: http://docs.python.org/library/itertools.html#itertools-recipes

from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

You would then it use like this:

for x, y in grouper(my_set, 2, 0.0):  # Use 0.0 to pad with a float
    print(x, y)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRasmus Damgaard NielsenView Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonjamylakView Answer on Stackoverflow
Solution 3 - PythonLllamaView Answer on Stackoverflow