Split lists and tuples in Python

十年热恋 提交于 2020-02-07 02:37:29

问题


I have a simple question.

I have list, or a tuple, and I want to split it into many lists (or tuples) that contain the same elements.

I'll try to be more clear using an example:

(1,1,2,2,3,3,4) --> (1,1),(2,2),(3,3),(4,)

(1,2,3,3,3,3) --> (1,),(2,),(3,3,3,3)

[2,2,3,3,2,3] --> [2,2],[3,3],[2],[3]

How can I do? I know that tuples and lists do not have the attribute "split" so i thought that i could turn them into strings before. This is what i tried:

def splitt(l)
    x=str(l)
    for i in range (len(x)-1):
        if x[i]!=x[i+1]:
            x.split()
    return x

回答1:


You can use groupby.

import itertools as it

[list(grp) if isinstance(t,list) else tuple(grp) for k, grp in it.groupby(t)]

Examples:

>>> t = (1,2,3,3,3,3) 
[(1,), (2,), (3, 3, 3, 3)]

>>> t = [2,2,3,3,2,3]
[[2, 2], [3, 3], [2], [3]]



回答2:


You also may try with for-loop:

def group_lt(list_or_tuple):
    result = []
    for x in list_or_tuple:
        if not result or result[-1][0] != x:
            result.append(type(list_or_tuple)([x]))
        else:
            result[-1] += type(list_or_tuple)([x])
    return result

t = (1,1,2,2,3,3,4)
print(group_lt(t))  # [(1,1),(2,2),(3,3),(4,)]

l = [2,2,3,3,2,3]    
print(group_lt(l))  # [[2,2],[3,3],[2],[3]]



回答3:


Try this

from itertools import groupby

input_list = [1, 1, 2, 4, 6, 6, 7]
output = [list(g) for k, g in groupby(input_list)]


来源:https://stackoverflow.com/questions/59922061/split-lists-and-tuples-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!