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

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

本问题已经有最佳答案,请猛点这里访问。

我有一个类似的集合(669256.02,6117662.09,669258.61,6117664.39,669258.05,6117665.08),我需要迭代它,比如

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

哪个可以打印

1
2
3
    669256.02 6117662.09
    669258.61 6117664.39
    669258.05 6117665.08

即时消息在python 3.3 btw上


您可以使用迭代器:

1
2
3
4
5
6
7
8
>>> 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

1
2
3
4
5
6
7
8
>>> 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


itertools食谱部分中的grouper示例可以帮助您:http://docs.python.org/3.3/library/itertools.html itertools食谱

1
2
3
4
5
6
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)

然后您将使用:

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