Python:如何基于定界符将列表拆分为未知数量的较小列表 [英] Python: how to split a list into an unknown number of smaller lists based on a delimeter

查看:177
本文介绍了Python:如何基于定界符将列表拆分为未知数量的较小列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下字符串的列表:

I've got a list which contains the following strings:

主列表
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

MainList
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

每当遇到"00:00"时,我都希望将其拆分为较少的列表,因为"00:00"是唯一不会更改的元素:

I would like to split this into a smaller number of lists whenever '00:00' is encountered since '00:00' is the only element that won't change:

所需输出:
列表1
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

Desired output:
List1
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

列表2
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

List2
'00:00'
'00:01'
'00:02'
'00:03'
'00:04'

我尝试查看列表切片,但问题是最后一个值以及这样的元素数量可能会改变.而且,我不确定我需要多少个较小的列表(以及如何动态创建n个较小的列表?)

I tried looking at list slicing but the problem is that the last value and as such, number of elements may change. Moreover, I'm not sure how many smaller lists I'll need (and how I'd dynamically create n number of smaller lists?)

推荐答案

我通常这样做:

def splitby( lst, breaker='00:00'):
    current = []
    it = iter(lst)
    first = next(it)
    assert first==breaker, "`lst` must begin with `breaker`"
    for item in it:
        if item == breaker:
            yield current
            current = []
        current.append(item)
    yield current

不可避免的itertools解决方案更为通用:

The inevitable itertools solution is a bit more general:

from itertools import groupby

class splitter(object):

    def __init__(self, breaker):
        self.breaker = breaker
        self.current_group = 0

    def __call__(self, item):
        if item == self.breaker:
            self.current_group+=1
        return self.current_group

    def group(self, items):
        return (list(v) for k,v in groupby(items,self))

print list(splitter('00:00').group(items))

这篇关于Python:如何基于定界符将列表拆分为未知数量的较小列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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