使用基础python将数字列表中的连续数字分组为元组列表(不允许使用itertools或更多itertools) [英] Group consecutive numbers from a list of numbers into a list of tuples using base python (NO itertools or more itertools allowed)

查看:39
本文介绍了使用基础python将数字列表中的连续数字分组为元组列表(不允许使用itertools或更多itertools)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想列出一个这样的列表:

I would like to turn a list like this:

L1 = [3、5、6、7、8、9、11、13、14]

进入一组连续数字,其中每个组都是使用基本python的元组(不允许使用itertools或更多itertools).

Into a list of groups of consecutive numbers where each group is a tuple using base python (NO itertools or more itertools allowed).

最终列表应如下所示: [(3,),(5,6,7,8,9),(11,),(13,14)]

Final list should look like this: [(3,), (5, 6, 7, 8, 9), (11,), (13, 14)]

我通过使用 more_itertools

import more_itertools as mit

[tuple(group) for group in mit.consecutive_groups(sorted(L1))]

结果: [(3,),(5,6,7,8,9),(11,),(13,14)]

推荐答案

使用生成器( conecutive_groups 是生成器):

L1 = [3, 5, 6, 7, 8, 9, 11, 13, 14]


def group_consecutive(l):
    r = []
    for e in l:
        if not r:
            r.append(e)
        elif e - r[-1] == 1:
            r.append(e)
        else:
            yield tuple(r)
            r = [e]
    yield tuple(r)


print(list(group_consecutive(L1)))  # [(3,), (5, 6, 7, 8, 9), (11,), (13, 14)]

生成器并使用列表切片:

Generator and using List slicing:

L1 = [3, 5, 6, 7, 8, 9, 11, 13, 14]


def group_consecutive(l):
    start = 0
    stop = 0
    for i, e in enumerate(l):
        if not stop or l[i] - l[i-1] == 1:
            stop += 1
        else:
            yield tuple(l[start:stop])
            start = i
            stop = i + 1
    yield tuple(l[start:stop])


print(list(group_consecutive(L1)))  # [(3,), (5, 6, 7, 8, 9), (11,), (13, 14)]

这篇关于使用基础python将数字列表中的连续数字分组为元组列表(不允许使用itertools或更多itertools)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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