Home > Back-end >  Extract patterns from tuples
Extract patterns from tuples

Time:07-27

I have a list of tuples

 a=[('a', 0), ('c', 1), ('d', 0), ('b', 1), ('t',1), ('j',2), ('k',3), ('s', 4), ('l',1), ('y',1), ('r',2), ('b',3), ('k',4)]

I want output like

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

and corresponding letters

 [['c', 'b', 't', 'j', 'k', 's'], ['l', 'y', 'r', 'b', 'k']]

I need to remove 0's in between and the pattern always starts with 1

CodePudding user response:

Using a simple loop and tracking the previous non-zero value:

letters = []
numbers = []
prev = 2
for l,n in a:
    if n == 0:
        continue
    elif prev > 1 and n == 1:
        letters.append([])
        numbers.append([])
    letters[-1].append(l)
    numbers[-1].append(n)
    prev = n

letters
# [['c', 'b', 't', 'j', 'k', 's'], ['l', 'y', 'r', 'b', 'k']]

numbers
# [[1, 1, 1, 2, 3, 4], [1, 1, 2, 3, 4]]
  • Related