Yuzuriha Inori
Yuzuriha Inori

Reputation: 165

Need to partition a list into parts following a specific rule

I have the following list of lists (the inner lists will be referred to as tuples henceforth, just to avoid confusion) :

[[1, 1], [2, 1], [2, 2], [3, 1], [3, 2], [4, 1], [3, 3], [4, 2], [5, 1], [4, 3], [5, 2], [6, 1], [4, 4], [5, 3], [6, 2], [7, 1]]

and I would like to create another list that contains:

[[[1, 1]], [[2, 1], [2, 2]], [[3, 1], [3, 2]], [[4, 1], [3, 3], [4, 2]], [[5, 1], [4, 3], [5, 2]], [[6, 1], [4, 4], [5, 3], [6, 2]], [[7, 1]]]

What basically I am doing is scanning the list of tuples, and putting the tuples into sublists until I hit a tuple that has a higher first coordinate than the previous tuples (italics is a correction based on a comment, I had meant this but while writing, missed it). For example the first element is [1,1] and the next is [2,1], but since 2>1, the first sublist is [[1,1]]. Then again, when we hit [3,1], the second sublist created is [[2,1],[2,2]] and so on.

How do I implement this in python? Specifically python 3?

Upvotes: 0

Views: 60

Answers (2)

Mario Camilleri
Mario Camilleri

Reputation: 1557

The following solution assumes that the input data is never an empty list:

d  = [[1, 1], [2, 1], [2, 2], [3, 1], [3, 2], [4, 1], [3, 3], [4, 2], [5, 1], [4, 3], [5, 2], [6, 1], [4, 4], [5, 3], [6, 2], [7, 1]]

d2 = [[d[0]]]
for t in d[1:]:
  if t[0] > d2[-1][0][0]:
    d2.append([t])
  else:
    d2[-1].append(t)

print(d2)

The following accommodates the case where the input data is an empty list:

d2 = []
for t in d:
  if (not d2) or (t[0] > d2[-1][0][0]):
    d2.append([t])
  else:
    d2[-1].append(t)

Upvotes: 2

Onyambu
Onyambu

Reputation: 79238

a = [[1, 1], [2, 1], [2, 2], [3, 1], [3, 2], [4, 1], [3, 3], [4, 2], [5, 1], [4, 3], [5, 2], [6, 1], [4, 4], [5, 3], [6, 2], [7, 1]]

def cummax(v):
    x = v[:1]
    for i in v:
       x.append(x[-1] if x[-1] > i else i)
    return x

d = {} 
for i,j in zip(cummax([i for i,j in a]), a):
    if not d.get(i):
        d[i]=[]
    d[i].append(j)
list(d.values())

[[[1, 1]], [[2, 1], [2, 2]], [[3, 1], [3, 2]], [[4, 1], [3, 3], [4, 2]], [[5, 1], [4, 3], [5, 2]], [[6, 1], [4, 4], [5, 3], [6, 2]], [[7, 1]]]

Upvotes: 1

Related Questions