B
B
beduin012020-09-03 14:27:08
Python
beduin01, 2020-09-03 14:27:08

How to find and group elements in a row?

I have if a sequence of characters (let each element be a string)
aa lot bb obj obj obj cc lot obj gg lot obj obj

I need to find out how many objects are in each lot. And get something like the output:
[lot 3 obj] [lot 1 obj] [lot 2 obj]

There is garbage in the string - all other characters except obj and lot. We do not take it into account. The delimiter of each section is a new `lot`.

How to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-09-03
@0xD34F

separator = 'lot'
item = 'obj'
count = [ n.count(item) for n in s.split(separator)[1:] ]

print(' '.join(f'[{separator} {n} {item}]' for n in count))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question