Ana Barroso
Ana Barroso

Reputation: 11

How to split a tuple into sub-tuples based on a condition in Python?

I have a list like this [1,2,1,1,2,3,3]. I want to separate this tuple into sub-tuples according to:

[1,2,1,1] [2,1,1,2] [3,3]

So the condition to separate the vector is when the first number of the tuple repeats itself for the last time.

How can I do this?

Upvotes: 1

Views: 356

Answers (2)

Frenchy
Frenchy

Reputation: 17027

a simple program:

l = (1,2,1,1,2,3,3)
r=[]
for i in set(l):
    li = len(l) - 1 - l[::-1].index(i)   #last index of item
    lf = l.index(i)                      #first index of item
    r.append((l[lf:li+1]))

print(r)

result:

[(1, 2, 1, 1), (2, 1, 1, 2), (3, 3)]

Upvotes: 1

mozway
mozway

Reputation: 261850

You can read the elements and collect the first and last index per element as you go.

Then slice your list accordingly:

l = [1,2,1,1,2,3,3]

d = {}
for i, v in enumerate(l): # for each value in the input
    if v not in d:      # if the value was not yet seen
        d[v] = [i, i+1] # record its position and the next in d
    else:               # if the value was already seen
        d[v][1] = i+1   # update its last position (+1 for inclusive slicing)

out = {k: l[slice(*v)] for k,v in d.items()}

output (here as a dictionary):

{1: [1, 2, 1, 1],
 2: [2, 1, 1, 2],
 3: [3, 3]}

Upvotes: 2

Related Questions