如何将列表分组为包含性顺序n元组 [英] How to group a list into inclusive sequential n-tuples

查看:71
本文介绍了如何将列表分组为包含性顺序n元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在Python中将列表作为对(当前,下一个)进行迭代

Possible Duplicate:
Iterate a list as pair (current, next) in Python

我有一个这样的列表:

list = [A, B, C, D, E, F, G]

如何将其分组以获取以下Python输出

How can I group this to get the following Python output

[(A,B), (B,C), (C, D), (D,E), (E,F), (F,G)]

因此这些值按次值分组,但顺序保留下来...

So the values are grouped by the secound value but the order is preserved...

推荐答案

尝试使用zip():

zip(lst, lst[1:])

此外,您不应使用名称list,因为您将覆盖内置列表类型.

Also, you shouldn't use the name list, as you will override the built-in list type.

示例:

>>> lst = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
>>> zip(lst, lst[1:])
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]

对于适用于生成器或其他单次迭代的版本,可以使用

For a version that will work with generators or other one-pass iterables, you can use the pairwise recipe from the itertools docs:

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

这篇关于如何将列表分组为包含性顺序n元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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