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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16789776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:41:29  来源:igfitidea点击:

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

pythonlist

提问by Rasmus Damgaard Nielsen

I have a set like (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08) which I need to iterate over, 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)

which would print

哪个会打印

    669256.02 6117662.09
    669258.61 6117664.39
    669258.05 6117665.08

im on Python 3.3 btw

我在 Python 3.3 上顺便说一句

采纳答案by Ashwini Chaudhary

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

回答by jamylak

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

回答by Lllama

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

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