遍历列表中的每两个元素 [英] Iterating over every two elements in a list

查看:695
本文介绍了遍历列表中的每两个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进行for循环或列表理解,以便每次迭代都给我两个元素?

How do I make a for loop or a list comprehension so that every iteration gives me two elements?

l = [1,2,3,4,5,6]

for i,k in ???:
    print str(i), '+', str(k), '=', str(i+k)

输出:

1+2=3
3+4=7
5+6=11

推荐答案

您需要实现 pairwise() (或 grouped() ).

You need a pairwise() (or grouped()) implementation.

对于Python 2:

For Python 2:

from itertools import izip

def pairwise(iterable):
    "s -> (s0, s1), (s2, s3), (s4, s5), ..."
    a = iter(iterable)
    return izip(a, a)

for x, y in pairwise(l):
   print "%d + %d = %d" % (x, y, x + y)

或更笼统地说:

from itertools import izip

def grouped(iterable, n):
    "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
    return izip(*[iter(iterable)]*n)

for x, y in grouped(l, 2):
   print "%d + %d = %d" % (x, y, x + y)

在Python 3中,您可以替换 izip 使用内置的 zip() 函数,然后将.

In Python 3, you can replace izip with the built-in zip() function, and drop the import.

martineau -a-python-dictionary-from-a-line-of-text/4356415#4356415>他的回答对我问题,我发现这非常有效,因为它仅对列表进行一次迭代,并且在此过程中不会创建任何不必要的列表.

All credit to martineau for his answer to my question, I have found this to be very efficient as it only iterates once over the list and does not create any unnecessary lists in the process.

注意事项:请勿将其与"> @lazyr 指出,strong> itertools 文档会生成s -> (s0, s1), (s1, s2), (s2, s3), .... >在评论中.

N.B: This should not be confused with the pairwise recipe in Python's own itertools documentation, which yields s -> (s0, s1), (s1, s2), (s2, s3), ..., as pointed out by @lazyr in the comments.

对于那些想在Python 3上使用 mypy 进行类型检查的人来说,几乎没有什么补充.

Little addition for those who would like to do type checking with mypy on Python 3:

from typing import Iterable, Tuple, TypeVar

T = TypeVar("T")

def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]:
    """s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ..."""
    return zip(*[iter(iterable)] * n)

这篇关于遍历列表中的每两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆