65

我有一个像 (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08) 这样的集合,我需要对其进行迭代,比如

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

这将打印

    669256.02 6117662.09
    669258.61 6117664.39
    669258.05 6117665.08

我在 Python 3.3 顺便说一句

4

3 回答 3

107

您可以使用迭代器:

>>> 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
于 2013-05-28T10:32:14.637 回答
33
>>> 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
于 2013-05-28T10:32:53.723 回答
13

食谱部分 中的grouper示例应该在这里对您有所帮助:http: //docs.python.org/library/itertools.html#itertools-recipesitertools

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)

然后你会像这样使用它:

for x, y in grouper(my_set, 2, 0.0):  # Use 0.0 to pad with a float
    print(x, y)
于 2013-05-28T10:34:46.497 回答