python - 遍历列表中的每两个元素

如何制作 for 循环或列表推导式,以便每次迭代都给我两个元素?

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())实现。

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

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

或者,更一般地说:

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 zip(*[iter(iterable)]*n)

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

在 Python 2 中,您应该导入 izip作为 Python 3 内置 zip() 的替代品功能。

全部归功于 martineau对于 his answer至my question ,我发现这非常有效,因为它只在列表上迭代一次,并且不会在此过程中创建任何不必要的列表。

注意:这不应与 pairwise recipe 混淆。在 Python 自己的 itertools documentation ,产生 s -> (s0, s1), (s1, s2), (s2, s3), ...,正如 @lazyr 所指出的那样在评论中。

对于那些希望在 Python 3 上使用 mypy 进行类型检查的人来说,这是一个小小的补充:

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)

https://stackoverflow.com/questions/5389507/

相关文章:

linux - 在 Linux 上的 bash 中获取昨天的日期,DST 安全

linux - 如何在不覆盖 TTY 的情况下将密码传递给 su/sudo/ssh?

python - 在 NumPy 中将索引数组转换为 one-hot 编码数组

python - 如何用下划线替换空格?

linux - 如何在 linux 中显示来自 bash 脚本的 GUI 消息框?

python - Python中的事件系统

linux - 如何强制 CIFS 连接卸载

linux - 递归删除文件

linux - 在 SSH session 中查找客户端的 IP 地址

python - 如何为 popen 指定工作目录