user12750510
user12750510

Reputation:

Split lists and tuples in Python

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

Upvotes: 0

Views: 81

Answers (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)]

Upvotes: 1

Giannis Clipper
Giannis Clipper

Reputation: 707

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]]

Upvotes: 1

abc
abc

Reputation: 11929

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]]

Upvotes: 1

Related Questions