迭代Python中的类似项目组

时间:2015-03-19 22:38:52

标签: python

在给定顺序中在大型列表中生成类似项目组的最有效方法是什么?例如:[' a'' b',' b'' c'' c',&# 39; c',' b',' c'' c'] - > [[' A&#39],[' B'' B&#39],[' C'' C' ' C&#39],[' b&#39],[' C'' C']]

我目前的解决方案是使用一个简单的迭代器并在列表中工作。这很好用。但我很想知道更好的选择。特别是在处理包含100万条或更多条目的非常长的列表时。

def grouper(items):
    grp = []
    for i in items:
        if grp and i != grp[-1]:
            if grp:
                yield grp
            grp = [i]
        else:
            grp.append(i)

    if grp:
        yield grp        

new = []
for x in grouper(['a','b','b','c','c','c','b','c','c']):
    # Do something useful with this group
    for x in grouper(data):
        print '#>>>%s'%x

#>>>['a']
#>>>['b', 'b']
#>>>['c', 'c', 'c']
#>>>['b']
#>>>['c', 'c']

0 个答案:

没有答案