在python中一次迭代列表的两个值

2024-04-25 17:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个集合like(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.3btw上的im


Tags: inforlikeprintimbtw
3条回答

itertools菜谱部分中的grouper示例应该可以帮助您: 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)

然后你会这样使用:

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

可以使用迭代器:

>>> 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
>>> 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

相关问题 更多 >